Esempio n. 1
0
def get_stats():
    mcr = MCRcon("0.0.0.0", "factory")
    mcr.connect()
    resp = mcr.command(write_stats_command)
    #do something with the response
    mcr.disconnect()
    return resp
Esempio n. 2
0
def send_commands(server_ip, rcon_password, commands, buyer, rcon_port):
    server_ip = str(server_ip).split(':')[0]
    mcr = MCRcon(server_ip, rcon_password, int(rcon_port))
    mcr.connect()
    for command in commands:
        mcr.command(command.replace("{PLAYER}", buyer))
    mcr.disconnect()
Esempio n. 3
0
class RconInterface:
    def __init__(self, ip_address, port, password, name="None"):
        self.con = MCRcon(ip_address, password, port=port)
        self.name = name
        try:
            self.con.connect()
        except ConnectionRefusedError:
            print(f'rcon failed to connect {self.con.host}:{self.con.port}')

    def getstatus(self):
        return str(self.con.socket).find("0.0.0.0") == -1

    def reconnect(self):
        if not self.getstatus():
            self.con.connect()

    def command(self, command, retrys=0):
        try:
            return self.con.command(command)
        except (ConnectionResetError, ConnectionRefusedError):
            self.con.connect()
            if retrys < 5:
                self.command(command, retrys + 1)

    def __del__(self):
        self.con.disconnect()
Esempio n. 4
0
def execute_rcon_commands(host):
    mcr = MCRcon(host=host.host, password=host.rcon_pass, port=host.rcon_port)
    mcr.connect()
    try:
        yield mcr
    except:
        mcr.disconnect()
        raise
    else:
        mcr.disconnect()
Esempio n. 5
0
def main():
    print("Factocli RCON Client Started")
    print("Connecting to RCON Address")
    mcr = MCRcon("0.0.0.0", "factory")
    mcr.connect()
    resp = mcr.command(write_stats_command)
    print("Sending command...")
    print("Response: "+resp)
    print("Disconnecting...")
    mcr.disconnect()
    print("Done")
Esempio n. 6
0
def check_rcon_connection(server_ip, rcon_password, rcon_port):
    try:
        new_server_ip = str(server_ip).split(':')[0]
        print(new_server_ip)
        mcr = MCRcon(new_server_ip, rcon_password, int(rcon_port))
        mcr.connect()
        mcr.disconnect()
        return True
    except Exception as e:
        print(e)
        return False
Esempio n. 7
0
def safe_MCRcon(host, password, port):
    try:
        mcr = MCRcon(host, password, port=port)
        mcr.connect()
    except ConnectionResetError as err:
        yield None, err
    else:
        try:
            yield mcr, None
        finally:
            mcr.disconnect()
Esempio n. 8
0
def check_shutoff(config):
    sum_players = 0

    server_store = open(config['server_store'], 'r')
    cached_statuses = json.loads(server_store.read())
    server_store.close()

    for key, val in cached_statuses.items():
        sum_players += sum(val)

    if config['debug']:
        print('========== Check shutoff ==========')
        pprint({'total_historical_num_players': sum_players})
        print()

    all_long_running = len(
        list(
            filter(
                lambda count: count != 3,
                list(
                    map(lambda server: len(cached_statuses[server]),
                        cached_statuses.keys()))))) == 0

    if sum_players == 0 and all_long_running:
        if config['debug']:
            print('========= Saving servers ==========')
        for server in cached_statuses.keys():
            try:
                host = config['servers'][server]['host']
                port = config['servers'][server]['port']
                password = config['servers'][server]['password']

                mcr = MCRcon(host=host, password=password, port=port)
                mcr.connect()

                resp = mcr.command('save-all')

                if config['debug']:
                    print(f'save-all response for {server}: {resp}')
                logging.info(f'save-all response for {server}: {resp}')

                mcr.disconnect()
            except Exception as e:
                logging.warning(
                    f'An error occured for server {server}\n{str(e)}')

        if config['debug']:
            print('===== Shutting down instance ======')
        else:
            with open(config['server_store'], 'w+') as server_store:
                server_store.write(json.dumps({}, indent=2))
            EC2 = boto3.client('ec2', region_name=config['region_name'])
            resp = EC2.stop_instances(InstanceIds=[config['instance_id']])
Esempio n. 9
0
async def whitelist_remove_user(user_id):
    rcon: tuple = await get_rcon()
    mcr = MCRcon(host=rcon[0], port=int(rcon[1]), password=rcon[2])

    mcr.connect()
    rcon_response = mcr.command(
        f'whitelist remove {await get_mc_username(user_id)}')
    print(rcon_response)
    mcr.disconnect()

    db.execute('DELETE FROM minecraft_users WHERE user_id=?', (user_id, ))
    connection.commit()
Esempio n. 10
0
class _RConsole:
    __lock_connection_action = Lock()
    __lock_auto_close_thread = Lock()

    __disconnect_seconds = 100

    def __init__(self, host, port: int, password, use_tls: bool = True):
        tls = {
            True: 1,
            False: 0
        }
        self.__auto_close_timer = AsyncCountdownTimer(self.__disconnect_seconds, self.__disconnect)
        self.__con = MCRcon(host, password, port, tls[use_tls])

    def execute(self, command: str, timeout: int = 0) -> str:
        """
        Execute a command, return its response. :param command: the command to be executed. :param timeout: timeout
        in seconds. If it is set to 0, the function waits until a response is received. If timed out,
        an `TimedOutException` will be thrown. :return: the response echo.
        """
        # check connection
        with self.__lock_connection_action:
            if not self.__con.socket:
                self.__con.connect()
        with self.__lock_auto_close_thread:
            self.__auto_close_timer.reset()
            self.__auto_close_timer = AsyncCountdownTimer(self.__disconnect_seconds, self.__disconnect)
            self.__auto_close_timer.start()

        # TODO: implement timeout
        if timeout:
            raise NotImplementedError("Sorry, timeout has not been implemented")

        # execute command
        logging.info(f'Execute command: {command}')
        return self.__con.command(command)

    def __del__(self):
        if self.__auto_close_timer:
            self.__auto_close_timer.reset()

    def __disconnect(self):
        disconnected = False
        with self.__lock_connection_action:
            if self.__con.socket:
                self.__con.disconnect()
                disconnected = True
        if disconnected:
            logging.info('Console is inactive. Disconnected from RCON server.')
Esempio n. 11
0
class Scoreboard(object):
    def __init__(self, host, password, port=25575):
        self.rcon = MCRcon(host, password, port=port)

    def __enter__(self):
        self.rcon.connect()

        return self

    def __exit__(self, type, value, tb):
        self.rcon.disconnect()

    def get_value_for_player(self, nickname: str, score: str) -> int:
        cmd_result = self.rcon.command('scoreboard players get {} {}'.format(
            nickname, score))
        value = cmd_result[cmd_result.find('has') + 4:cmd_result.find('[') - 1]
        return int(value)
Esempio n. 12
0
 async def whitelist(ctx):
     if rconIp == "":
         await ctx.author.send(
             "please run $setup before using any commmands")
         return False
     if ctx.channel.id == CHANNELID or CHANNELID == 0:
         if poll(ctx.author.id) == False:
             first_set = await query(ctx)
             #print("done with first set: " + str(first_set[0]) + str(first_set[1]) + str(first_set[2]) + str(first_set[3]))
             if first_set != False:
                 second_set = await newsletterQuery(ctx)
                 #print("done with second set: " + str(second_set))
                 if second_set != False:
                     conn = psycopg2.connect(database=pgdb,
                                             user=pgUser,
                                             password=pgPass,
                                             host=pgHost,
                                             port=pgPort)
                     cur = conn.cursor()
                     try:
                         #print("------------showing insert to database---------\nuser_id:"+str(ctx.author.id)+"\nfirst_name:"+str(first_set[0])+"\nlast_name:"+str(first_set[1])+"\nuuid:"+str(first_set[2])+"\nusername:"******"\nemail:"+str(second_set))
                         cur.execute(
                             'INSERT INTO whitelist ("user_id", "first_name", "last_name", "uuid", "username", "email", "isBanned") VALUES ('
                             + str(ctx.author.id) + ', \'' +
                             str(first_set[0]) + '\', \'' +
                             str(first_set[1]) + '\', N\'' +
                             str(first_set[2]) + '\', N\'' +
                             str(first_set[3]) + '\', N\'' +
                             str(second_set) + '\', ' + str(0) + ');')
                         conn.commit()
                     except Exception as e:
                         print("DB error: \n" + str(e))
                     mcr = MCRcon(str(rconIp),
                                  str(rconPass),
                                  port=int(rconPort))
                     mcr.connect()
                     resp = mcr.command("whitelist add " +
                                        str(first_set[3]))
                     print(resp)
                     mcr.disconnect()
                     await ctx.author.send(embed=addFinish_embed)
                     conn.close()
         else:
             if poll(ctx.author.id)[6] == 0:
                 await edit(ctx)
Esempio n. 13
0
    async def remove(ctx):
        if rconIp == "":
            await ctx.author.send(
                "please run $setup before using any commmands")
            return False
        if ctx.channel.id == CHANNELID or CHANNELID == 0:
            if poll(ctx.author.id) != False:
                if poll(ctx.author.id)[6] == 0:
                    username = ctx.author
                    msgPrompt = await username.send(
                        embed=removeConfirmPrompt_embed)
                    thumbsup, thumbsdown = '👍', '👎'
                    await msgPrompt.add_reaction(thumbsup)
                    await msgPrompt.add_reaction(thumbsdown)

                    def checkreact(reaction, react):
                        react = str(reaction.emoji)
                        return ((react == '👍' or react == '👎')
                                and (reaction.message.id == msgPrompt.id))

                    await asyncio.sleep(.1)
                    try:
                        confirmation = await bot.wait_for('reaction_add',
                                                          check=checkreact,
                                                          timeout=300)
                    except TimeoutError:
                        print(
                            "User " + str(ctx.author) +
                            "Timed out on removal confirmation, User remains in database"
                        )
                        await ctx.author.send(embed=timeout_embed)
                        return False
                    else:
                        if str(confirmation[0].emoji) == '👍':
                            mcUser = poll(username.id)[4]
                            mcr = MCRcon(str(rconIp),
                                         str(rconPass),
                                         port=int(rconPort))
                            mcr.connect()
                            resp = mcr.command("whitelist remove " + mcUser)
                            print(resp)
                            mcr.disconnect()
                            remove_player(username.id)
                            await username.send(embed=removeConfirm_embed)
Esempio n. 14
0
async def whitelist_add_user(user_id, username):
    rcon: tuple = await get_rcon()
    mcr = MCRcon(host=rcon[0], port=int(rcon[1]), password=rcon[2])
    mcr.connect()

    if await has_whitelist(user_id):
        rcon_response = mcr.command(
            f'whitelist remove {await get_mc_username(user_id)}')
        print(rcon_response)
        db.execute('UPDATE minecraft_users SET mc_username=? WHERE user_id=?',
                   (username, user_id))
    else:
        db.execute('INSERT INTO minecraft_users VALUES(?,?)',
                   (user_id, username))
    connection.commit()

    rcon_response = mcr.command(f'whitelist add {username}')
    print(rcon_response)
    mcr.disconnect()
Esempio n. 15
0
 async def __stop_server(self, channel: channel, ctx: Context):
     self.status = 'stopping'
     try:
         s = socket.socket()
         s.settimeout(3)
         s.connect(("server address", 25565))
         s.close()
         mc = MCRcon('server address', '**********')
         mc.connect()
         await self.shutdown(mc)
         mc.disconnect()
     except:
         await channel.send(
             '> :warning: **Couldn\'t connect to mc-server. Shutting down directly**'
         )
     thread = Thread(target=get, args=(addr, 'shutdown'))
     thread.start()
     await channel.send("> :octagonal_sign: **Stopping server**")
     while thread.is_alive():
         await delay(0.5)
     await channel.send('> :octagonal_sign: **Server is stopped**')
     self.status = 'terminated'
Esempio n. 16
0
def sendRconCommands(cmds, delay = 0.03):
    mcr = MCRcon("127.0.0.1", _rconPass, _rconPort, 0)

    try:
        mcr.connect()
    except Exception as ex:
        logmsg(f'ERROR: Unable to connect to rcon server: {ex}')
        return

    # flatten all commands
    cmds = [item for sublist in cmds for item in sublist]

    for cmd in cmds:
        try:
            resp = mcr.command(cmd)
            logmsg(f'RCON Command: {cmd}: {resp}')
            time.sleep(delay)
        except Exception as ex:
            logmsg(f'ERROR: Unable to send rcon command: {cmd}')
            logmsg(f'       {ex}')
            break

    mcr.disconnect()
Esempio n. 17
0
def Shutdown():
    if not request.headers.get("User-Agent") == USER_AGENT:
        error_message = {"state": 0, "error": "Invalid User-Agent."}
        return make_response(jsonify(error_message), 400)
    if not request.headers.get("Content-Type") == CONTENT_TYPE:
        error_message = {"state": 0, "error": "Invalid Content-Type."}
        return make_response(jsonify(error_message), 400)
    try:
        mcr = MCRcon(IPADDRESS, PASSWORD, RCONPORT)
        mcr.connect()
        resp = mcr.command("saveworld")
        mcr.command(
            "Broadcast The world has been saved. The server will be shutdown in 1 minute."
        )
        time.sleep(60)
        resp = mcr.command("saveworld")
        mcr.command("Broadcast Stop the server.")
        mcr.command("DoExit")
        print(resp)
        mcr.disconnect()
    except:
        pass
    session = winrm.Session(IPADDRESS, auth=(USER, PASSWORD))
    try:
        session.run_ps("shutdown -s -f -t 120")
        success_message = {
            "state": 1,
            "body": "The request was executed successfully."
        }
    except:
        success_message = {
            "state":
            0,
            "body":
            "The request was processed successfully, but the shutdown process was not executed properly.",
        }
    return make_response(jsonify(success_message), 200)
Esempio n. 18
0
    async def on_ready():
        print("starting bot and setting config")
        #load_dotenv()
        global prefix
        global CHANNELID
        global rconIp
        global rconPort
        global rconPass
        conn = psycopg2.connect(database=pgdb,
                                user=pgUser,
                                password=pgPass,
                                host=pgHost,
                                port=pgPort)
        cur = conn.cursor()
        cur.execute('SELECT * FROM serverconfig;')
        a = cur.fetchone()
        conn.close()
        if a != None:
            print('showing server stuff: \nserver: ' + str(a[0]) +
                  '\nchannel_id:' + str(a[1]) + '\nprefix:' + str(a[2]) +
                  '\nip:' + str(a[3]) + '\nport:' + str(a[4]) + '\npass:' +
                  str(a[5]))
        if a != None:
            bot.command_prefix = str(a[2])
            CHANNELID = int(a[1])
            rconIp = str(a[3])
            rconPort = int(a[4])
            rconPass = str(a[5])
            mcr = MCRcon(str(rconIp), str(rconPass))
            mcr.connect()
            resp = mcr.command("/help")
            print(resp)
            mcr.disconnect()
        else:
            print("please run $setup")

        print("Bot ready")
Esempio n. 19
0
class MCServerAdmin:
    def __init__(self, ip=None, rcon_port=None, rcon_pass=None):
        self.tk_window = tk.Tk()
        self.tk_style = ttk.Style(self.tk_window)
        self.tk_window.withdraw()

        if not ip and not rcon_port and not rcon_pass:
            self.generate_login_ui()
        else:
            self.connectToServer(ip, rcon_port, rcon_pass)
            self.generate_main_ui()
        self.tk_window.mainloop()

    def generate_main_ui(self):
        self.tk_window.deiconify()
        self.tk_window.title(f"PyMineCraft Administration - {self.ip}:{self.port}")

        commandLabel = ttk.Label(self.tk_window, text="Enter a command: ")
        commandLabel.grid(column=0, row=0, padx=10, pady=10, sticky='w')
        commandInput = ttk.Entry(self.tk_window, width=50)
        commandInput.grid(column=0, row=1, padx=10, pady=10, sticky='w')
        sendCommandButton = ttk.Button(self.tk_window, command=lambda: self.processCommand(commandInput.get()) or commandInput.delete(0, len(commandInput.get())),
                                       text='Send Command')
        sendCommandButton.grid(column=0, row=2, padx=10, pady=10, sticky='w')
        self.tk_window.bind('<Return>', lambda x: self.processCommand(commandInput.get()) or commandInput.delete(0, len(commandInput.get())))

        serverResponseLabel = ttk.Label(self.tk_window, text="Server Response:")
        serverResponseLabel.grid(column=0, row=3, padx=10, pady=10, sticky='w')
        self.serverResponseText = ttk.Label(self.tk_window, text="N/A")
        self.serverResponseText.grid(column=0, row=4, padx=10, pady=10, sticky='NSEW')

    def generate_login_ui(self):
        self.tk_window.deiconify()
        self.tk_window.title("PyMineCraft Administration - Login")

        serverIPLabel = ttk.Label(self.tk_window, text="Minecraft Server IP: ")
        serverIPLabel.grid(column=0, row=0, padx=10, pady=10, sticky='w')
        serverIPInput = ttk.Entry(self.tk_window)
        serverIPInput.grid(column=0, row=1, padx=10, pady=10, sticky='w')
        rconPortLabel = ttk.Label(self.tk_window, text="RCON Port: ")
        rconPortLabel.grid(column=1, row=0, padx=10, pady=10, sticky='w')
        rconPortInput = ttk.Entry(self.tk_window)
        rconPortInput.grid(column=1, row=1, padx=10, pady=10, sticky='w')
        rconPasswordLabel = ttk.Label(self.tk_window, text="RCON Password: "******"Server Connectivity - ERROR", "The Minecraft Server RCON port must be an integer (1-65535)")
            raise ValueError("The Minecraft Server RCON port must be an integer (1-65535)")
        self.mcr_instance = MCRcon(host=self.ip, port=self.port, password=rcon_pass)
        self.mcr_instance.connect()
        if self.mcr_instance:
            messagebox.showinfo("Server Connectivity - Success", "Successfully connected to the server!")
            self.resetWindow()
            self.generate_main_ui()
        else:
            messagebox.showinfo("Server Connectivity - Failed", "Failed connecting to the server!")

    def resetWindow(self):
        self.tk_window.destroy()
        self.tk_window = tk.Tk()
        self.tk_style = ttk.Style(self.tk_window)

    def processCommand(self, command):
        if self.mcr_instance:
            cmd_input = command.strip()
            if len(cmd_input) == 0:
                return
            elif cmd_input == "!quit":
                self.exit()
                return
            elif cmd_input[0] != "/":
                resp = f"> {cmd_input}"
                cmd_input = f"say {cmd_input}"
                self.mcr_instance.command(cmd_input)
            else:
                cmd_input = cmd_input[1:]
                resp = self.mcr_instance.command(cmd_input)
            print(resp)
            if self.serverResponseText:
                self.serverResponseText.config(text=resp)

    def exit(self):
        if self.mcr_instance:
            self.mcr_instance.disconnect()
        if self.tk_window:
            self.tk_window.destroy()
Esempio n. 20
0
class MainCog(commands.Cog, name="main"):
    def __init__(self, bot: DioCraft):
        super().__init__()

        self.mcr = MCRcon(server_ip, server_password, int(server_port))

        try:
            self.mcr.connect()
        except:
            print("Unexpected error: {}".format(sys.exc_info()[0]))
            self.mcr.disconnect()

        self.bot = bot

    @commands.command()
    async def login(self, ctx: commands.Command):
        allowed_roles = ["Admins"]
        if (await self.privilegeCheck(ctx, allowed_roles)
                and await self.channelCheck(ctx)):
            channel = self.bot.get_channel(729513577186066473)
            try:
                self.mcr.connect()
                await channel.send(
                    "Successfully logged into the Minecraft server.")
            except:
                await channel.send("Unexpected error: {}".format(
                    sys.exc_info()[0]))
                self.mcr.disconnect()

    @commands.command()
    async def awl(self, ctx: commands.Command):
        allowed_roles = ["Minecraft", "Admins"]
        if (await self.privilegeCheck(ctx, allowed_roles)
                and await self.channelCheck(ctx)):
            player_name = ctx.message.content[5:]
            resp = self.mcr.command("/whitelist add {}".format(player_name))
            await ctx.send(resp)

    @commands.command()
    async def dwl(self, ctx: commands.Command):
        allowed_roles = ["Admins"]
        if (await self.privilegeCheck(ctx, allowed_roles)
                and await self.channelCheck(ctx)):
            player_name = ctx.message.content[5:]
            resp = self.mcr.command("/whitelist remove {}".format(player_name))
            await ctx.send(resp)

    @commands.command()
    async def wl(self, ctx: commands.Command):
        if (await self.channelCheck(ctx)):
            await self.listWhitelist(ctx)

    @commands.command()
    async def online(self, ctx: commands.Command):
        if (await self.channelCheck(ctx)):
            await self.listPlayers(ctx)

    @commands.command()
    async def help(self, ctx: commands.Command):
        if (await self.channelCheck(ctx)):
            msg = "Thank you for using DioCraft! It is still currently under development :)\n\n"
            msg += "/online - Display list of all players that are online.\n"
            msg += "/wl - Display list of all players that are whitelisted.\n"
            msg += "/awl <name> - To add someone to the server whitelist.\n"
            msg += "/dwl <name> - To remove someone from the server whitelist.\n\n"
            msg += "/login - For administrators to connect to the server.\n\n"
            msg += "If you have any questions or suggestions, please contact primal#7602! Thank you!"
            await ctx.send(msg)

    async def privilegeCheck(self, ctx: commands.Command, allowed_roles):
        is_admin = False

        for role in ctx.message.author.roles:
            if (role.name in allowed_roles):
                is_admin = True

        if (not is_admin):
            await ctx.send("{}, does not have permission.".format(
                ctx.message.author.display_name))

        return is_admin

    async def channelCheck(self, ctx: commands.Command):
        is_channel = False
        allowed_channels = [729859164209283104, 729513577186066473]
        # Change this to list to hold more channels.
        if (ctx.message.channel.id in allowed_channels):
            is_channel = True

        return is_channel

    async def listWhitelist(self, ctx: commands.Command):
        resp = self.mcr.command("/whitelist list").split(" ")
        result = "```The following {} players are whitelisted:\n".format(
            resp[2])
        resp = resp[5:]
        lastName = resp[len(resp) - 1]
        resp = resp[:-1]

        for name in resp:
            result += name[:-1] + "\n"

        result += lastName + "```"

        await ctx.send(result)

    async def listPlayers(self, ctx: commands.Command):
        resp = self.mcr.command("/list").split(" ")
        result = "```There {} players online:\n".format(resp[2])
        resp = resp[10:]
        lastName = resp[len(resp) - 1]
        resp = resp[:-1]

        for name in resp:
            result += name[:-1] + "\n"

        result += lastName + "```"

        await ctx.send(result)
Esempio n. 21
0
class MinecraftPlayerLocation:
    rcon_connected = False

    def __init__(self, mcrcon_host, mcrcon_password, mcrcon_port, fps):
        self.timeout = 1 / int(fps)
        self.mcrcon = MCRcon(mcrcon_host, mcrcon_password, mcrcon_port)
        self.online_players = []
        self.message = {}

        self.refresh_rcon()
        threading.Thread(target=self.get_message).start()

    def parse_players(self):
        rcon_playerlist = self.mcrcon.command('list')
        try:
            _, players = rcon_playerlist.split(':')
        except ValueError:
            players = ''
        if players.strip():
            self.online_players = [
                player.strip() for player in players.split(', ')
            ]
        else:
            self.online_players = []

    def refresh_rcon(self):
        self.mcrcon.disconnect()
        rcon_connected = False
        sleep(1)
        while not rcon_connected:
            try:
                self.mcrcon.connect()
                rcon_connected = True
                self.parse_players()
                print('Connection to rcon established!')
            except ConnectionRefusedError:
                print('Coudn\'t connect to rcon. I\'ll try again in a sec!',
                      file=sys.stderr)
                sleep(1)
                self.refresh_rcon()

    def parse_player_locations(self):
        self.parse_players()
        for player in self.online_players:
            rcon_pos = self.mcrcon.command(f'data get entity {player} Pos')
            rcon_dimension = self.mcrcon.command(
                f'data get entity {player} Dimension')
            try:
                _, dimension = rcon_dimension.split(':', 1)
                _, coords = rcon_pos.split(':')
                x, y, z = coords.strip().replace('[',
                                                 '').replace(']', '').replace(
                                                     'd', '').split(', ')
            except ValueError:
                dimension = ''
                x = y = z = 0
            cleaned_dimension = dimension.strip()
            yield player, {
                'name': player,
                'x': x,
                'y': y,
                'z': z,
                'dimension': cleaned_dimension
            }

    def get_message(self):
        while True:
            sleep(self.timeout)
            self.message = {
                player: info
                for player, info in self.parse_player_locations()
            }
Esempio n. 22
0
class RemoteConnection:
    # TODO: Create import system for json data to advancement_list

    def __init__(self, host=None, password=None):
        if host is not None and password is not None:
            self._host = host
            self._password = password
            self._client = MCRcon(host, password)
            self.connect()
        else:
            self._host = None
            self._password = None
            self._client = None

        self._adv_file, self.adv_categories = self._load_advancements()

    def _get_advancement(self, category, general_name):
        return self._adv_file[self.adv_categories[category]][general_name]

    def _load_advancements(self):
        return json.loads(open('advancements.json').read()), list(json.loads(open('advancements.json').read()))

    def connect(self):
        if self._client is None:
            if self._host is not None and self._password is not None:
                self._client = MCRcon(self._host, self._password)
            else:
                self.set_host(input("Enter Host IP: "))
                self.set_password(input("Enter Password: "))
                self._client = MCRcon(self._host, self._password)

            self._client.connect()
        else:
            self._client.connect()

    def disconnect(self):
        self._client.disconnect()

    def set_host(self, host_data):
        self._host = host_data

    def set_password(self, password_data):
        self._password = password_data

    def advancement(self, action_choice, target, advancement_target_choice, advancement):
        actions = ['grant', 'revoke']
        advancement_targets = ['only', 'until', 'from', 'through', 'everything']
        # Make a json file with all the advancements and have a method decode and set this key-pair

        action = actions[action_choice]
        advancement_target = advancement_targets[advancement_target_choice]

        if action == 'grant':
            if advancement_target == 'only':
                sub_cmd = target + ' ' + 'only ' + 'minecraft:' + advancement['id']

            elif advancement_target == 'until':
                pass
            elif advancement_target == 'from':
                pass
            elif advancement_target == 'through':
                pass
            elif advancement_target == 'everything':
                pass
            else:
                pass
            cmd = 'grant ' + sub_cmd
        elif action == 'revoke':
            pass

        return self._client.command('/advancement ' + cmd)

    def ban(self, targets, reason='No reason given!'):
        return self._client.command('/ban ' + targets + ' ' + reason)

    def ban_ip(self, target, reason):
        return self._client.command('/ban ' + target + ' ' + reason)

    def banlist(self, choice):
        pass

    def bossbar(self, choice):
        pass

    def clear(self):
        pass

    def clone(self):
        pass

    def data(self):
        pass

    def datapack(self):
        pass

    def debug(self):
        pass

    def defaultgamemode(self):
        pass

    def deop(self, player):
        return self._client.command('/deop ' + player)

    def difficulty(self, choice):
        pass

    def effect(self, choice):
        pass

    def enchant(self, enchantment, level, target=...):
        pass

    def execute(self, choice):
        pass

    def experience(self, choice):
        pass

    def fill(self):
        pass

    def function(self):
        pass

    def gamemode(self, gamemode_choice, target):
        gamemodes = ['survival', 'creative', 'adventure', 'spectator']

        mode = gamemodes[gamemode_choice]

        return self._client.command('/gamemode ' + mode + ' ' + target)

    def gamerule(self):
        pass

    def give(self):
        pass

    def help(self):
        pass

    def kick(self):
        pass

    def kill(self):
        pass

    def list(self):
        pass

    def locate(self):
        pass

    def me(self):
        pass

    def msg(self):
        pass

    def op(self, player):
        return self._client.command('/op ' + player)

    def pardon(self, target):
        return self._client.command('/pardon ' + target)

    def pardon_ip(self):
        pass

    def particle(self):
        pass

    def playsound(self):
        pass

    def recipe(self):
        pass

    def reload(self):
        pass

    def replaceitem(self):
        pass

    def save_all(self):
        pass

    def save_off(self):
        pass

    def save_on(self):
        pass

    def say(self, message):
        print(self._client.command('/say ' + message))

    def scoreboard(self):
        pass

    def seed(self):
        pass

    def setblock(self):
        pass

    def setidletimeout(self):
        pass

    def setworldspawn(self):
        pass

    def spawnpoint(self):
        pass

    def spreadplayers(self):
        pass

    def stop(self):
        pass

    def stopsound(self):
        pass

    def summon(self):
        pass

    def tag(self):
        pass

    def team(self):
        pass

    def teleport(self):
        pass

    def tell(self):
        pass

    def tellraw(self):
        pass

    def time(self):
        pass

    def title(self):
        pass

    def tp(self):
        pass

    def w(self):
        pass

    def weather(self, weather_choice=0, duration=None):
        weather_conditions = ['clear', 'rain', 'thunder']

        return self._client.command('/weather ' + weather_conditions[weather_choice])

    def whitelist(self):
        pass

    def worldborder(self):
        pass

    def xp(self):
        pass
Esempio n. 23
0
from mcrcon import MCRcon
import subprocess, time, socket

a_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
location = ("127.0.0.1", 25565)
result_of_check = a_socket.connect_ex(location)
if result_of_check == 0:
    a_socket.close()
    print("server gia\' avviato")
    time.sleep(5)
else:
    a_socket.close()
    print("server in avvio")
    processo = subprocess.Popen(["java", "-jar", "spigot-1.16.3.jar"],
                                stdout=subprocess.PIPE)
    for i in range(30):
        print(".", end='')
        time.sleep(1)

mcr = MCRcon("127.0.0.1", "password")
mcr.connect()
resp = "Connessione"
print("\n" + resp)
while resp != "Stopping the server" or resp == "":
    comando = input('>')
    resp = mcr.command(comando)
    print(resp)
mcr.disconnect()
Esempio n. 24
0
    async def edit(ctx):
        while True:
            await ctx.author.send(embed=editMCPrompt_embed)

            def check(m):
                return m.author == ctx.author and m.channel.type == discord.ChannelType.private

            try:
                mcUser = await bot.wait_for('message',
                                            check=check,
                                            timeout=300)
            except TimeoutError:
                print("User " + str(ctx.author) +
                      "Timed out on edit query, Username remains unchanged")
                await ctx.author.send(embed=timeout_embed)
                return False
            else:
                mcUser = mcUser.content
                uuid = MojangAPI.get_uuid(mcUser)
                if not uuid:
                    await ctx.author.send(embed=UserNotFound_embed)
                    continue
                elif uuidPoll(uuid):
                    if uuidPoll(uuid)[0] == ctx.author.id:
                        await ctx.author.send(embed=linked_embed)
                        return False
                    await ctx.author.send(embed=existsEmbed(mcUser))
                    continue
                else:
                    msgPrompt = await ctx.author.send(
                        embed=usernameConfirmation(mcUser))
                    thumbsup, thumbsdown = '👍', '👎'
                    await msgPrompt.add_reaction(thumbsup)
                    await msgPrompt.add_reaction(thumbsdown)

                    def checkreact(reaction, react):
                        react = str(reaction.emoji)
                        return ((react == '👍' or react == '👎')
                                and (reaction.message.id == msgPrompt.id))

                    await asyncio.sleep(.1)
                    try:
                        confirmation = await bot.wait_for('reaction_add',
                                                          check=checkreact,
                                                          timeout=300)
                    except TimeoutError:
                        print(
                            "User " + str(ctx.author) +
                            "Timed out on edit confirmation, Username remains unchanged"
                        )
                        await ctx.author.send(embed=timeout_embed)
                        return False
                    else:
                        if str(confirmation[0].emoji) == '👍':
                            tempName = poll(ctx.author.id)[4]
                            #print("changing username: "******"uuid" = N\'' +
                                        str(uuid) + '\', "username" = N\'' +
                                        str(mcUser) + '\' WHERE "user_id" = ' +
                                        str(ctx.author.id) + ';')
                            conn.commit()
                            mcr = MCRcon(str(rconIp),
                                         str(rconPass),
                                         port=int(rconPort))
                            mcr.connect()
                            resp = mcr.command("whitelist remove " + tempName)
                            print(resp)
                            resp = mcr.command("whitelist add " + mcUser)
                            print(resp)
                            mcr.disconnect()
                            await ctx.author.send(embed=editConfirm(mcUser))
                            conn.close()
                            return True
Esempio n. 25
0
        ['tail', '-n', '1', '/root/server/logs/latest.log'], encoding='utf-8')

    matches = re.search(r'<(.*?)> (.*)', latest)

    if matches is None:
        time.sleep(0.5)
        continue

    name = matches.group(1)
    typed = matches.group(2)

    idx = typed.find(' ')
    if idx != -1:
        cmd = typed[:idx].lower()
        args = typed[idx + 1:].lower()
    else:
        cmd = typed.lower()
        args = None

    try:
        command = callbacks[cmd]
    except KeyError:
        continue

    try:
        command(name, args)
    except:
        rcon.say('You typed the command wrong Pepega :)')

rcon.disconnect()
Esempio n. 26
0
def update_player_numbers(config):
    new_statuses = {}

    for server in config['servers'].keys():

        host = config['servers'][server]['host']
        port = config['servers'][server]['port']
        password = config['servers'][server]['password']
        players_online = 0

        try:
            mcr = MCRcon(host=host, password=password, port=port)
            mcr.connect()

            players_online = mcr.command('list')
            players_online = re.sub(r'(§[0-9]|§[a-z])', '', players_online)
            players_online = int(re.search(r'\d+|$', players_online).group())

            mcr.disconnect()
        except Exception as e:
            logging.warning(f'{host}:{port} could not be reached.\n{str(e)}')

        new_statuses[server] = players_online

    server_store = open(config['server_store'], 'r')
    cached_statuses = json.loads(server_store.read())
    server_store.close()

    if config['debug']:
        print('========= Loaded statuses =========')
        pprint(cached_statuses)
        print()

    for server in set(new_statuses.keys()).union(cached_statuses.keys()):
        if server in new_statuses and server in cached_statuses:
            cached_statuses[server].append(new_statuses[server])
            cached_statuses[server] = cached_statuses[server][-3:]

        elif server in new_statuses and server not in cached_statuses:
            logging.info(
                f'Found server {server} from config, adding to cached statuses list'
            )
            cached_statuses[server] = [new_statuses[server]]

        elif server not in new_statuses and server in cached_statuses:
            if len(cached_statuses[server]) == 3 and sum(
                    cached_statuses[server]) == 0:
                logging.warning(
                    f'Dropping check for server {server} due to inactivity')
                del cached_statuses[server]
            else:
                cached_statuses[server].append(0)
                cached_statuses[server] = cached_statuses[server][-3:]

        else:
            raise (Exception('Something\'s fucky'))

    server_store = open(config['server_store'], 'w')
    server_store.write(json.dumps(cached_statuses, indent=2))
    server_store.close()

    if config['debug']:
        print('======== Updated statuses =========')
        pprint(cached_statuses)
        print()
Esempio n. 27
0
class worldeatercommands(commands.Cog):
    def __init__(self, client):
        self.client = client
        self.rcon_smp = MCRcon(config_rcon['rcon_smp']['rcon-ip'],
                               config_rcon['rcon_smp']['rcon-password'],
                               config_rcon['rcon_smp']['rcon-port'])
        self.coords = ()
        self.peri_size = 0
        self.worldeater_crashed = False
        self.we_updates = False
        self.ylevel = 0

    @commands.Cog.listener()
    async def on_ready(self):
        print('worldeatercommands is online.')
        self.guild = self.client.get_guild(config_discord['guild'])
        self.we_channel = discord.utils.get(
            self.guild.text_channels, id=config_discord["worldeater_channel"])

    @commands.command(
        help=
        'Use this to start the worldeater script. Arguments: peri_size , mandatory<x,z>. x and z argument: Postion on any part of worldeater with no blocks above it. Height control is now necessary'
    )
    @commands.has_any_role('Member', 'Trial-Member')
    async def westart(self, ctx, peri_size: int, *coords):
        if self.check_worldeater.is_running():
            await ctx.send(embed=discord.Embed(
                title='World eater is already running', color=0xFF0000))
            return
        self.peri_size = peri_size
        if len(coords) == 2:
            self.coords = coords
            self.rcon_smp.connect()
            resp = self.rcon_smp.command(
                f'/script run top(\'surface\',{self.coords[0]}, 0, {self.coords[1]})'
            )
            self.ylevel = int(resp.split()[1]) + 1
            cycletime = peri_size / 2
            self.check_worldeater.change_interval(seconds=cycletime)
            self.check_worldeater.start()
            title = 'Worldeater is now running'
            msg = f'The peri size is: {peri_size}\n' \
                  f'Coordinates for height control: x={coords[0]} y={coords[1]}'

        else:
            self.coords = ()
            title = 'Command was done incorrectly'
            msg = f'You are running without height control'
        await ctx.send(
            embed=discord.Embed(title=title, colour=0xFF0000, description=msg))

    @commands.command(help='stops the world eater script')
    @commands.has_any_role('Member', 'Trial-Member')
    async def westop(self, ctx):
        if not self.check_worldeater.is_running():
            await ctx.send(embed=discord.Embed(
                title='No world eater is running', color=0xFF0000))
            return
        self.check_worldeater.cancel()
        self.check_worldeater.stop()
        self.coords = ()
        self.peri_size = 0
        self.worldeater_crashed = False
        self.we_updates = False
        self.ylevel = 0
        await ctx.send(embed=discord.Embed(
            title=f'World eater script is stopped now',
            colour=0x00FF00,
        ))

    @commands.command(help='use this to get info about the world eater')
    @commands.has_any_role('Member', 'Trial-Member')
    async def westatus(self, ctx):
        if not self.check_worldeater.is_running():
            await ctx.send(embed=discord.Embed(
                title='No world eater is running', color=0xFF0000))
            return

        if self.worldeater_crashed:
            title = 'World eater is stuck'
            color = 0xFF0000
        else:
            title = 'World eater is running'
            color = 0x00FF00

        if not self.coords:
            self.rcon_smp.connect()
            resp = self.rcon_smp.command(
                f'/script run reduce(last_tick_times(),_a+_,0)/100;')
            mspt = float(resp.split()[1])
            msg = f'MSPT is ~{round((mspt),1)}\n' \
                   'You are running without height control'
        else:
            self.rcon_smp.connect()
            resp = self.rcon_smp.command(
                f'/script run top(\'surface\',{self.coords[0]}, 0, {self.coords[1]})'
            )
            yLevel = int(resp.split()[1]) + 1
            timeleft = str(
                datetime.timedelta(seconds=(self.peri_size / 2) *
                                   (yLevel - 5)))
            self.rcon_smp.connect()
            resp = self.rcon_smp.command(
                f'/script run reduce(last_tick_times(),_a+_,0)/100;')
            mspt = float(resp.split()[1])
            msg = f'y-level: ~{yLevel}\n' \
                  f'WE has to run for another ~{timeleft}\n' \
                  f'MSPT is ~{round((mspt),1)}'
            self.rcon_smp.disconnect()
        await ctx.send(
            embed=discord.Embed(title=title, colour=color, description=msg))

    @commands.command(
        help=
        'get or remove worldeater role. you get pinged if worldeater crashes')
    @commands.has_any_role('Member', 'Trial-Member')
    async def wehelper(self, ctx):
        we_role = get(self.guild.roles, name=config_discord['worldeater_role'])
        if not we_role in ctx.message.author.roles:
            await ctx.message.author.add_roles(we_role)
            await ctx.send('You now get pinged if a world eater crashes')
        else:
            await ctx.message.author.remove_roles(we_role)
            await ctx.send('You are no longer a world eater helper')

    @commands.command(help='get live updates on world eater progress')
    @commands.has_any_role('Member', 'Trial-Member')
    async def weupdates(self, ctx):
        if not self.check_worldeater.is_running():
            await ctx.send(embed=discord.Embed(
                title='No world eater is running', color=0xFF0000))
            return
        if self.we_updates:
            await ctx.send(embed=discord.Embed(title='Live updates turned off',
                                               color=0xFF0000))
        else:
            await ctx.send(embed=discord.Embed(title='Live updates turned on',
                                               color=0x00FF00))
        self.we_updates = not self.we_updates

    @tasks.loop()
    async def check_worldeater(self):
        self.rcon_smp.connect()
        self.ylevel = yLevel
        resp = self.rcon_smp.command(
            f'/script run top(\'surface\',{self.coords[0]}, 0, {self.coords[1]})'
        )
        resp = int(resp.split()[1]) + 1
        if resp < ylevel:
            self.ylevel = ylevel - 1
            if not resp < yLevel:
                if not self.worldeater_crashed:
                    await asyncio.sleep(20)
                    self.rcon_smp.connect()
                    resp = self.rcon_smp.command(
                        f'/script run top(\'surface\',{self.coords[0]}, 0, {self.coords[1]})'
                    )
                    resp = int(resp.split()[1]) + 1
                    if not resp < ylevel:
                        role = get(self.guild.roles,
                                   name=config_discord['worldeater_role'])
                        await self.we_channel.send(
                            f'{role.mention} World eater is stuck.')
                        self.worldeater_crashed = True
                        self.check_worldeater.change_interval(seconds=10)
            elif self.worldeater_crashed:
                self.worldeater_crashed = False
                self.check_worldeater.change_interval(seconds=self.peri_size /
                                                      2)
                self.ylevel = ylevel - 1
                await self.we_channel.send(f'World eater is fine again.')
            if self.we_updates and not self.worldeater_crashed:
                if not self.coords:
                    msg = 'still running'
                else:
                    self.rcon_smp.connect()
                    resp = self.rcon_smp.command(
                        f'/script run top(\'surface\',{self.coords[0]}, 0, {self.coords[1]})'
                    )
                    yLevel = int(resp.split()[1]) + 1
                    timeleft = str(
                        datetime.timedelta(seconds=(self.peri_size / 2) *
                                           (yLevel - 5)))
                    self.rcon_smp.connect()
                    resp = self.rcon_smp.command(
                        f'/script run reduce(last_tick_times(),_a+_,0)/100;')
                    mspt = float(resp.split()[1])
                    msg = f'y-level: ~{yLevel}\n' \
                          f'WE has to run for another ~{timeleft}\n' \
                          f'MSPT is ~{round((mspt), 1)}'
                    self.rcon_smp.disconnect()
                await self.we_channel.send(embed=discord.Embed(
                    title='WE Updates', colour=0x00FF00, description=msg))
            self.rcon_smp.disconnect()