Пример #1
0
def mega_bomb(pl, adress, port, password):
    with MCRcon(adress, password, port=port) as mcr:
        a = mcr.command('execute at ' + pl +
                        ' run summon creeper ~ ~ ~ {powered:1, count:3} ')
        return a[:8] == "Summoned"
Пример #2
0
"""
Simple Rcon module.
If a server runs on localhost with rcon enabled and port and password set as below, unit tests will test the datapack
on this server automatically
"""
import atexit

from mcrcon import MCRcon

HOST = "localhost"
PORT = 25575
PASSWORD = "******"

connected: bool = False
rcon: MCRcon = MCRcon(HOST, PASSWORD, PORT)
atexit.register(rcon.disconnect)


def createConnection():
    global connected
    if not connected:
        rcon.connect()
        connected = True


def send(command: str) -> str:
    createConnection()
    return rcon.command(command)
Пример #3
0
def online(update, context):
    """Send a message when the command /online is issued."""
    with MCRcon(mc_server_ip, mc_rcon_password) as mcr:
        resp = mcr.command("/list")
        update.message.reply_text(resp)
        print(resp)
Пример #4
0
 def __init__(self, bot):
     self.bot = bot
     self.rcon = MCRcon(RCON_ADDR, RCON_PASS, RCON_PORT)
     self.rcon.connect()
     self.am = AccountManager()
    def get_server_stats(self):
        if not all(x in os.environ for x in ['RCON_HOST', 'RCON_PASSWORD']):
            return []
        dim_tps = Metric('dim_tps', 'TPS of a dimension', "counter")
        dim_ticktime = Metric('dim_ticktime',
                              "Time a Tick took in a Dimension", "counter")
        overall_tps = Metric('overall_tps', 'overall TPS', "counter")
        overall_ticktime = Metric('overall_ticktime', "overall Ticktime",
                                  "counter")
        player_online = Metric('player_online', "is 1 if player is online",
                               "counter")
        entities = Metric('entities', "type and count of active entites",
                          "counter")
        mcr = MCRcon(os.environ['RCON_HOST'],
                     os.environ['RCON_PASSWORD'],
                     port=int(os.environ['RCON_PORT']))
        mcr.connect()

        # dimensions
        resp = mcr.command("forge tps")
        dimtpsregex = re.compile(
            "Dim\s*(-*\d*)\s\((.*?)\)\s:\sMean tick time:\s(.*?) ms\. Mean TPS: (\d*\.\d*)"
        )
        for dimid, dimname, meanticktime, meantps in dimtpsregex.findall(resp):
            dim_tps.add_sample('dim_tps',
                               value=meantps,
                               labels={
                                   'dimension_id': dimid,
                                   'dimension_name': dimname
                               })
            dim_ticktime.add_sample('dim_ticktime',
                                    value=meanticktime,
                                    labels={
                                        'dimension_id': dimid,
                                        'dimension_name': dimname
                                    })
        overallregex = re.compile(
            "Overall\s?: Mean tick time: (.*) ms. Mean TPS: (.*)")
        overall_tps.add_sample('overall_tps',
                               value=overallregex.findall(resp)[0][1],
                               labels={})
        overall_ticktime.add_sample('overall_ticktime',
                                    value=overallregex.findall(resp)[0][0],
                                    labels={})

        # entites
        resp = mcr.command("forge entity list")
        entityregex = re.compile("(\d+): (.*?:.*?)\s")
        for entitycount, entityname in entityregex.findall(resp):
            entities.add_sample('entities',
                                value=entitycount,
                                labels={'entity': entityname})

        # player
        resp = mcr.command("list")
        playerregex = re.compile("There are \d*\/20 players online:(.*)")
        if playerregex.findall(resp):
            for player in playerregex.findall(resp)[0].split(","):
                if player:
                    player_online.add_sample(
                        'player_online',
                        value=1,
                        labels={'player': player.lstrip()})

        return [
            dim_tps, dim_ticktime, overall_tps, overall_ticktime,
            player_online, entities
        ]
Пример #6
0
    port = 25575
    filename = None
    passwd = None

    try:
        addr = sys.argv[1]
        if ':' in addr:
            spl = addr.split(':')
            addr = spl[0]
            port = int(spl[1])

        passwd = sys.argv[2]
        filename = sys.argv[3]
        coords[0] = int(sys.argv[4])
        coords[1] = int(sys.argv[5])
        coords[2] = int(sys.argv[6])
        if 'air' in sys.argv:
            skip_air = True

    except IndexError:
        print(
            "Usage: mcpaste.py rcon_host[:port] rcon_passwordcd schematic_file x y z [air]"
        )
        sys.exit(1)

    schm = schematic.MCSchematic(filename=filename)
    print('Schematic length ' + str(schm.Length) + ' width ' +
          str(schm.Width) + ' height ' + str(schm.Height))
    rcon = MCRcon(addr, port, passwd)
    trip(schm)
Пример #7
0
    async def on_active(self, args: List[int], message: Message, bot: Client):

        if len(args) == 0:
            await message.channel.send(
                random.choice([
                    "300%BOT — Powered by Alex Bot",
                    "Try `help @300%Bot` :nicehj:"
                ]))
            return 0

        if not self.processing_stop:

            if args in (['launch', 'server'], ['run',
                                               'server'], ['start', 'server'],
                        ['server', 'start'], ['server',
                                              'launch'], ['server', 'run'],
                        ['launch'], ['run'], ['start'], ['play']):
                state = await fetch(API_SERVER + '/server/status')
                if state == "RUNNING":
                    await message.channel.send(embed=Embed(
                        description="**:warning: Server is already running!**",
                        colour=0xfff300))
                    return 0
                elif state == "LAUNCHING":
                    await message.channel.send(embed=Embed(
                        description=
                        "**:warning: Server is already launching!**",
                        colour=0xfff300))
                    return 0
                elif state == "STOPPING":
                    await message.channel.send(embed=Embed(
                        description=
                        "**:warning: You can't start the server while it's stopping!**",
                        colour=0xfff300))
                    return 0
                else:

                    await message.channel.send(embed=Embed(
                        description="**:rocket: Launching Server ...**",
                        colour=0x00ff00))
                    await fetch(API_SERVER + "/server/launch")
                    print("Done")
                    return 0

            elif args in (['status'], ['state']):
                result = await fetch(API_SERVER + "/server/status")
                if result == 'RUNNING':
                    msg = Embed(
                        description="**Server is running  :white_check_mark:**",
                        colour=0x00ff00)
                elif result == 'TERMINATED':
                    msg = Embed(
                        description="**Server is terminated :stop_sign:**",
                        colour=0xff0000)
                elif result == 'LAUNCHING':
                    msg = Embed(description="**Server is launching :rocket:**",
                                colour=0xd9f037)
                elif result == 'STOPPING':
                    msg = Embed(
                        description=
                        "**Server is stopping :small_red_triangle_down:**",
                        colour=0xf27a40)
                else:
                    msg = "I couldn't fetch server status!! :scream:"
                if type(msg) == Embed:
                    await message.channel.send(embed=msg)
                else:
                    await message.channel.send(msg)
                return 0
            elif args in (['shutdown',
                           'server'], ["shutdown"], ['stop', 'server'],
                          ['stop'], ['server', 'stop'], ['server', 'shutdown'],
                          ['turn', 'off', 'server'], ['server', 'turn',
                                                      'off'], ['turn', 'off'],
                          ['terminate', 'server'], ['server', 'terminate']):
                try:
                    s = socket()
                    s.settimeout(2)
                    s.connect((self.server_address, 25575))
                    s.close()
                    self.processing_stop = True
                    with MCRcon(self.server_address, PASSWORD) as rcon:
                        rcon.connect()
                        await message.channel.send(embed=Embed(
                            title=
                            ":warning: Server will shutdown in 15 secnods",
                            colour=0xfff300))
                        await rcon_message(rcon, [{
                            "text": "Server will stop in",
                            "color": "gold"
                        }, {
                            "text": " 15 ",
                            "color": "red"
                        }, {
                            "text": "seconds.",
                            "color": "gold"
                        }],
                                           sound=False)
                        await rcon_title(rcon, {
                            "text": "Server will stop",
                            "color": "gold"
                        }, {
                            "text": "in 15 secnods",
                            "color": "red"
                        })
                        await delay(10)
                        for i in range(5):
                            await delay(1)
                            await rcon_message(rcon, [{
                                "text": "Server will stop in",
                                "color": "gold"
                            }, {
                                "text": f" {5-i} ",
                                "color": "red"
                            }, {
                                "text": "seconds.",
                                "color": "gold"
                            }])
                        await rcon_message(rcon, [{
                            "text": "Stopping Server...",
                            "color": "gold"
                        }])
                except Exception as e:
                    print("Couldn't connect to server", e)
                self.processing_stop = False
                state = await fetch(API_SERVER + '/server/status')
                if state == "STOPPING":
                    await message.channel.send(embed=Embed(
                        description="**:warning: Server is already stopping!**",
                        colour=0xfff300))
                    return 0
                elif state == "TERMINATED":
                    await message.channel.send(embed=Embed(
                        description="**:warning: Server is already stopped!**",
                        colour=0xfff300))
                    return 0
                elif state == "LAUNCHING":
                    await message.channel.send(embed=Embed(
                        description=
                        "**:warning: You can't stop the server while it's launching!**",
                        colour=0xfff300))
                    return 0
                else:

                    await message.channel.send(embed=Embed(
                        description=
                        "**:small_red_triangle_down: Stopping Server ...**",
                        colour=0x00ff00))
                    await fetch("http://www.alex-xu.site:2000/server/terminate"
                                )
                    await message.channel.send(embed=Embed(
                        description="**:stop_sign: Server is stopped**",
                        colour=0xff5500))
                    return 0

        else:
            await message.channel.send(
                "Wait a second. I'm shutting down the server.")
            return 0

        return 1
    def get_server_stats(self):
        if not all(x in os.environ for x in ['RCON_HOST', 'RCON_PASSWORD']):
            return []
        dim_tps = Metric('dim_tps', 'TPS of a dimension', "counter")
        dim_ticktime = Metric('dim_ticktime',
                              "Time a Tick took in a Dimension", "counter")
        overall_tps = Metric('overall_tps', 'overall TPS', "counter")
        overall_ticktime = Metric('overall_ticktime', "overall Ticktime",
                                  "counter")
        player_online = Metric('player_online', "is 1 if player is online",
                               "counter")
        entities = Metric('entities', "type and count of active entites",
                          "counter")
        mcr = MCRcon(os.environ['RCON_HOST'],
                     os.environ['RCON_PASSWORD'],
                     port=int(os.environ['RCON_PORT']))
        mcr.connect()

        # dimensions
        resp = mcr.command("forge tps")
        dimtpsregex = re.compile(
            "Dim\s*(-*\d*)\s\((.*?)\)\s:\sMean tick time:\s(.*?) ms\. Mean TPS: (\d*\.\d*)"
        )
        for dimid, dimname, meanticktime, meantps in dimtpsregex.findall(resp):
            dim_tps.add_sample('dim_tps',
                               value=meantps,
                               labels={
                                   'dimension_id': dimid,
                                   'dimension_name': dimname
                               })
            dim_ticktime.add_sample('dim_ticktime',
                                    value=meanticktime,
                                    labels={
                                        'dimension_id': dimid,
                                        'dimension_name': dimname
                                    })
        overallregex = re.compile(
            "Overall\s?: Mean tick time: (.*) ms. Mean TPS: (.*)")
        overall_tps.add_sample('overall_tps',
                               value=overallregex.findall(resp)[0][1],
                               labels={})
        overall_ticktime.add_sample('overall_ticktime',
                                    value=overallregex.findall(resp)[0][0],
                                    labels={})

        # dynmap
        if os.environ['DYNMAP_ENABLED'] == "True":
            dynmap_tile_render_statistics = Metric(
                'dynmap_tile_render_statistics',
                'Tile Render Statistics reported by Dynmap', "counter")
            dynmap_chunk_loading_statistics_count = Metric(
                'dynmap_chunk_loading_statistics_count',
                'Chunk Loading Statistics reported by Dynmap', "counter")
            dynmap_chunk_loading_statistics_duration = Metric(
                'dynmap_chunk_loading_statistics_duration',
                'Chunk Loading Statistics reported by Dynmap', "counter")

            resp = mcr.command("dynmap stats")

            dynmaptilerenderregex = re.compile(
                "  (.*?): processed=(\d*), rendered=(\d*), updated=(\d*)")
            for dim, processed, rendered, updated in dynmaptilerenderregex.findall(
                    resp):
                dynmap_tile_render_statistics.add_sample(
                    'dynmap_tile_render_statistics',
                    value=processed,
                    labels={
                        'type': 'processed',
                        'file': dim
                    })
                dynmap_tile_render_statistics.add_sample(
                    'dynmap_tile_render_statistics',
                    value=rendered,
                    labels={
                        'type': 'rendered',
                        'file': dim
                    })
                dynmap_tile_render_statistics.add_sample(
                    'dynmap_tile_render_statistics',
                    value=updated,
                    labels={
                        'type': 'updated',
                        'file': dim
                    })

            dynmapchunkloadingregex = re.compile(
                "Chunks processed: (.*?): count=(\d*), (\d*.\d*)")
            for state, count, duration_per_chunk in dynmapchunkloadingregex.findall(
                    resp):
                dynmap_chunk_loading_statistics_count.add_sample(
                    'dynmap_chunk_loading_statistics',
                    value=count,
                    labels={'type': state})
                dynmap_chunk_loading_statistics_duration.add_sample(
                    'dynmap_chunk_loading_duration',
                    value=duration_per_chunk,
                    labels={'type': state})

        # entites
        resp = mcr.command("forge entity list")
        entityregex = re.compile("(\d+): (.*?:.*?)\s")
        for entitycount, entityname in entityregex.findall(resp):
            entities.add_sample('entities',
                                value=entitycount,
                                labels={'entity': entityname})

        # player
        resp = mcr.command("list")
        playerregex = re.compile("There are \d*\/20 players online:(.*)")
        if playerregex.findall(resp):
            for player in playerregex.findall(resp)[0].split(","):
                if player:
                    player_online.add_sample(
                        'player_online',
                        value=1,
                        labels={'player': player.lstrip()})

        return [
            dim_tps, dim_ticktime, overall_tps, overall_ticktime,
            player_online, entities, dynmap_tile_render_statistics,
            dynmap_chunk_loading_statistics_count,
            dynmap_chunk_loading_statistics_duration
        ]
Пример #9
0
import discord,os,json,re,asyncio,data
from mcrcon import MCRcon
from discord.ext import commands
from mcstatus import MinecraftServer
from discord.ext.commands import is_owner
from bot import adminOrOwner,logOutput
from discord_slash import cog_ext,SlashContext


save = data.load('save')
serverStarted = False
sizes={2:'MBs',3:'GBs'}
mainDirectory = os.getcwd()
serverQuery=os.getenv('serverQuery')
servers=data.load('servers')
mc=MCRcon(os.getenv('mcRconHost'),os.getenv('mcRconPassword'),int(os.getenv('mcRconPort')))

class serverMcstarter(commands.Cog):
	def __init__(self,client): self.client = client
	@cog_ext.cog_subcommand(base='minecraft',name='start',description='starts a minecraft server.')
	async def start(self,ctx:SlashContext,server:str):
		if serverStarted: return
		try: os.chdir(servers([server,'directory']))
		except: await ctx.send('server name error')
		os.startfile('botStart.bat')
		os.chdir(mainDirectory)
		await ctx.send('okay, it\'s starting.')
		for i in range(save.read(['servers',str(ctx.guild.id),'config','maxServerStartTime'])):
			try: MinecraftServer.lookup(serverQuery).query().players.online; break
			except: asyncio.sleep(1)
		else: await ctx.send('error starting server.'); return
Пример #10
0
                          fields: Dict[str, str]):
    return [{
        "measurement": measurement_name,
        "tags": tags,
        "time": RUN_TIME,
        "fields": fields
    }]


client = InfluxDBClient(host=INFLUX_SERVER_ADDR, port=INFLUX_SERVER_PORT)

client.create_database(MINECRAFT_DB_NAME)

client.switch_database(MINECRAFT_DB_NAME)

with MCRcon(MC_SERVER_ADDR, MC_SERVER_RCON_PASS, MC_SERVER_RCON_PORT) as rc:
    whitelist_response = rc.command("whitelist list")
    list_response = rc.command("list")

whitelist = whitelist_response[whitelist_response.find(":") + 1:].replace(
    ",", "").split()
print(whitelist)

online_players = list_response[list_response.find(":") + 1:].replace(
    ",", "").split()
print(online_players)

players_json = create_json_structure("players", {"server_id": SERVER_ID}, {
    "online_player_count": len(online_players),
    "online_players": ",".join(online_players)
})
Пример #11
0
 def __exec_cmd(self, cmd):
     with MCRcon(self.host, self.passw, port=self.port) as mcr:
         mcr.command(cmd)
Пример #12
0
 def __init__(self, bot):
     self.bot = bot
     self.mcr = MCRcon(os.environ["rcon_ip"], os.environ["rcon_pass"],
                       int(os.environ["rcon_port"]))
     self.mcr.connect()
Пример #13
0
async def send_message(text):
    with MCRcon(rcon_setting['address'], rcon_setting['password'], rcon_setting['port']) as mcr:
        r = mcr.command('tellraw @a {"extra":[{"text":"[","bold":true,"color":"gold"},{"text":"BOT","color":"dark_green"},{"text":"] ","bold":true,"color":"gold"},{"text":"' + text + '"}],"text":""}')
Пример #14
0
def lighting(pl, adress, port, password):
    with MCRcon(adress, password, port=port) as mcr:
        for i in range(3):
            a = mcr.command('execute at ' + pl +
                            ' run summon minecraft:lightning_bolt ~ ~ ~')
        return a[:8] == "Summoned"
Пример #15
0
def get_people_online():
    print("Getting list of players")
    with MCRcon("localhost", "ebbeh", port) as mcr:
        resp = mcr.command("/list")
        return int(resp.split(' ')[2])
    return 0
    light_brightness = b.get_light(light_id,
                                   'bri')  # Запоминаем яркость лампочки

    # Получаем от пользователя данные для подключеняи к серверу и ваш ник:
    rcon_ip = input('Введите rcon-ip сервера: ')
    rcon_port = int(input('Введите rcon-порт сервера: '))
    rcon_pass = input('Введите rcon-пароль сервера: ')
    player_name = input('Введите ник игрока: ')

    # Начинаем выполнение программы после нажатия ENTER
    input('Для старта нажмите ENTER...')

    # Пока программа не будет завершена пользователем (вечный цикл)...
    while True:
        # Отправляем на сервер майнкрафта запрос в виде команды нашего плагина и нашего ника
        with MCRcon(rcon_ip, rcon_pass, rcon_port) as mcr:
            resp = mcr.command(
                "lightsync " + player_name
            )  # Ответ будет сохранен в переменную resp типа String

            if (resp == 'E1\n') or (
                    resp == 'E0\n'):  # Если в resp окажется код ошибки...
                print(
                    '\nгрок не находится на сервере или никнейм введен с ошибкой'
                )  # Выдаем сообщение пользователю
                input(
                )  # Даем пользователю прочитать сообщение об ошибке, и после нажатия любой кнопки...
                break  # выходим из цикла, после чего программа будет завершена

            mc_lighlevel = int(
                resp
Пример #17
0
def use_stop_cmd():
    print("Stopping server " + instance + "!")
    with MCRcon("localhost", "ebbeh", port) as mcr:
        mcr.command("/save-all")
        mcr.command("/stop")
    return
Пример #18
0
    async def mcsetup(self, ctx):
        ip_confirmed = False
        rcon_password_confirmed = False
        rcon_port_confirmed = False
        channel_confirmed = False

        await ctx.send("**Welcome to Discord-Minecraft!**")
        await ctx.send(
            "You will now be taken through the setup process for this cog.")
        await asyncio.sleep(0.3)
        await ctx.send(".\n.\n.")
        try:
            while ip_confirmed == False:
                await ctx.send(
                    "Please enter the IP address of your minecraft server (without port)."
                )
                serverip = await self.bot.wait_for('message',
                                                   check=authorcheck(
                                                       ctx.message.author),
                                                   timeout=30)
                await ctx.send(
                    f"Please double check and ensure `{serverip.content}` is your servers IP address. Have you entered it correctly? y/n"
                )
                ip_check = await self.bot.wait_for('message',
                                                   check=authorcheck(
                                                       ctx.message.author),
                                                   timeout=30)
                if (ip_check.content).lower() == "y":
                    ip_confirmed = True
                    await self.config.guild(ctx.guild
                                            ).server_ip.set(serverip.content)
                    await ctx.send(
                        f"Successfully set `{serverip.content}` as the server IP."
                    )
                else:
                    ip_confirmed = False

            while rcon_port_confirmed == False:
                await ctx.send(".\n.\n.")
                await ctx.send(
                    "Please enter the RCON port for your server (Default 25575)."
                )
                rconport = await self.bot.wait_for('message',
                                                   check=authorcheck(
                                                       ctx.message.author),
                                                   timeout=30)
                await ctx.send(
                    f"Please double check and ensure `{rconport.content}` is your servers RCON port. Have you entered it correctly? y/n"
                )
                rcon_check = await self.bot.wait_for('message',
                                                     check=authorcheck(
                                                         ctx.message.author),
                                                     timeout=30)
                if (rcon_check.content).lower() == "y":
                    rcon_port_confirmed = True
                    await self.config.guild(ctx.guild).rcon_port.set(
                        int(rconport.content))
                    await ctx.send(
                        f"Successfully set `{rconport.content}` as the server RCON port."
                    )
                else:
                    rcon_port_confirmed = False

            while rcon_password_confirmed == False:
                await ctx.send(".\n.\n.")
                await ctx.send(
                    "Please enter the RCON password for your server.")
                rconpassword = await self.bot.wait_for('message',
                                                       check=authorcheck(
                                                           ctx.message.author),
                                                       timeout=30)
                rconpassword_temp = rconpassword
                await rconpassword.delete()
                await ctx.send(
                    f"Please double check and ensure ||{rconpassword_temp.content}|| is your servers RCON password. Have you entered it correctly? y/n"
                )
                rcon_pass_check = await self.bot.wait_for(
                    'message',
                    check=authorcheck(ctx.message.author),
                    timeout=30)
                if (rcon_pass_check.content).lower() == "y":
                    rcon_password_confirmed = True
                    await self.config.guild(ctx.guild).rcon_password.set(
                        rconpassword_temp.content)
                    await ctx.send(
                        f"Successfully set ||{rconpassword_temp.content}|| as the server RCON password."
                    )
                else:
                    rcon_password_confirmed = False

            await ctx.send(".\n.\n.")
            await ctx.send("Attempting to connect to server")
            await ctx.send(".\n.\n.")

            try:
                with MCRcon(
                    str(await self.config.guild(
                        ctx.guild
                    ).server_ip()),
                    str(await self.config.guild(
                        ctx.guild
                    ).rcon_password()),
                    int(await self.config.guild(
                        ctx.guild
                    ).rcon_port()))\
                            as mcr:

                    mcr.command(
                        "say TEST COMMAND WITH MINECRAFT-DISCORD COMMANDS")
                    await ctx.send(f"Successfully connected to server!")

                while channel_confirmed == False:
                    await ctx.send(".\n.\n.")
                    await ctx.send(
                        "Please enter the channel ID of the channel you wish to write commands in."
                    )
                    channelid = await self.bot.wait_for(
                        'message',
                        check=authorcheck(ctx.message.author),
                        timeout=30)
                    await ctx.send(
                        f"Please double check and ensure `{channelid.content}` is the correct channel ID. Have you entered it correctly? y/n"
                    )
                    channel_check = await self.bot.wait_for(
                        'message',
                        check=authorcheck(ctx.message.author),
                        timeout=30)
                    if (channel_check.content).lower() == "y":
                        channel_confirmed = True
                        await self.config.guild(ctx.guild
                                                ).commands_channel.set(
                                                    int(channelid.content))
                        await ctx.send(
                            f"Successfully set `{channelid.content}` as the commands channel ID."
                        )
                    else:
                        channel_confirmed = False

                    await ctx.send(".\n.\n.")
                    await ctx.send(
                        f"Setup complete! You can now use `{ctx.prefix}console` in <#{channelid.content}> to communicate with your Minecraft server's console."
                    )
                    await self.config.guild(ctx.guild).setup_complete.set(True)
            except (ConnectionRefusedError, TimeoutError,
                    MCRconException) as e:
                await ctx.send(
                    f"Connection failed with error ```{e}``` Please try again using `{ctx.prefix}mcsetup`"
                )

        except asyncio.TimeoutError:
            await ctx.send(
                f"{ctx.message.author.mention} You did not respond in time. To continue with your setup type `{ctx.prefix}mcsetup`"
            )
Пример #19
0
def execute(server, command):
    info = SERVERS[server]
    with MCRcon(info[0], MC_SECRET, port=info[1]) as mcr:
        print(mcr.command(command))
Пример #20
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()
Пример #21
0
def runMCCommand(command):
    with MCRcon('minecraft01-home.home.myhomelab.network', 'Remote1') as mcr:
        resp = mcr.command(command)
        resp = re.sub(r'§(\w|\d)?', '', resp)
        return resp
Пример #22
0
def print_running_test(request, server):
    with MCRcon(server.host, server.rcon_password, server.rcon_port) as mcr:
        # Set world spawn so that the set area is loaded
        mcr.command(f"/say Running test '{request.node.name}'")
Пример #23
0
def rcon_connect(server_name, config):
    rcon = MCRcon(config["servers"][server_name]["server_ip_numerical"],
                  config["servers"][server_name]["server_rcon_password"],
                  config["servers"][server_name]["server_rcon_port"])
    return rcon
Пример #24
0
import discord
import mcrcon
from discord.ext import commands
import datetime
from mcrcon import MCRcon
import json

with open("botdata.txt", "r") as datafile:
    data = json.load(datafile)

mcr = MCRcon(data["IP"], data["PW"])
user = data["USER"]


class cogname(commands.Cog, name='minecraft'):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(name="summon", pass_context=True)
    @commands.cooldown(1, 60, commands.BucketType.user)
    async def summon(self, ctx, mobname):
        mcr.connect()
        if mobname in ('ender_dragon', 'wither', 'ghast', 'blaze'):
            await ctx.send(" " + mobname +
                           " is not allowed on this server !  :flushed:")
            return
        else:
            await ctx.send("The command is sending... :desktop:")
            resp = mcr.command("execute at " + user + " run summon " +
                               mobname + " ~ ~ ~")
            mcr.disconnect()
Пример #25
0
app_port = config['App']['port']

# Create Flask instance
app = Flask(__name__, static_url_path='/static')
app.secret_key = config['App']['secret_key']
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SQLALCHEMY_DATABASE_URI'] = config['App']['database_uri']
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['RECAPTCHA_PUBLIC_KEY'] = recaptcha_public_key
app.config['RECAPTCHA_PRIVATE_KEY'] = recaptcha_private_key

# Connect to the database and create tables
database = SQLAlchemy(app)

# RCON
rcon = MCRcon()
rcon.connect(minecraft_rcon_host, minecraft_rcon_port, minecraft_rcon_password)

# Create bCrypt instance
bcrypt = Bcrypt(app)

# Create head manager for last buyers
heads = HeadManager()


# Database models
class Account(database.Model):
    __tablename__ = "accounts"

    id = database.Column('id', database.Integer, autoincrement=True, primary_key=True)
    name = database.Column('username', database.String(30), nullable=False, unique=True)
Пример #26
0
    async def status_fetch_task(self, bot):
        while not bot.is_closed():
            try:
                result = eval(await fetch("http://localhost:2005/ready"))
                if result != self.server_ready:
                    self.server_ready = result
                    if result:
                        await bot.get_channel(self.MC_CHANNEL).send(
                            embed=Embed(
                                title=f"SpaceCraft is ready",
                                description="**Server address:** __mc.alex-xu.site__",
                                colour=0x79f50a
                            )
                        )
                    else:
                        self.players = []
                        await bot.get_channel(self.MC_CHANNEL).send(
                            embed=Embed(
                                title=f"SpaceCraft is closed",
                                colour=0xff0000
                            )
                        )

                result = eval(await fetch("http://localhost:2005/players"))
                if result != self.players:
                    left = set(self.players) ^ set(result)
                    for player in left:
                        if player not in self.players:
                            await bot.get_channel(self.MC_CHANNEL).send(
                                embed=Embed(
                                    title=f"**{player}** join the server",
                                    colour=0x90c561
                                )
                            )
                            try:
                                s = socket()
                                s.settimeout(1)
                                s.connect((ADDRESS, 25575))
                                s.close()
                                with MCRcon(ADDRESS, PASSWORD) as rcon:
                                    rcon.connect()
                                    await rcon_title(
                                        rcon,
                                        {"text": "Welcome to", "color": "gold"},
                                        {"text": "SpaceCraft Server", "color": "blue"},
                                        mention=player
                                    )
                            except Exception as e:
                                print(e)
                        else:
                            await bot.get_channel(self.MC_CHANNEL).send(
                                embed=Embed(
                                    title=f"**{player}** left the server",
                                    colour=0xf7630c
                                )
                            )
                    self.players = result

                await delay(2)
            except Exception as e:
                await delay(3)
Пример #27
0
!pip install --upgrade pip
!pip install mcrcon

server_address = "your-container's FQDN is here.japaneast.azurecontainer.io"
server_passwd = "your password for Rcon"

from mcrcon import MCRcon

with MCRcon(server_address, server_passwd, 25575) as mcr:
    print(mcr.command("/time set night"))
    start_x, start_y, start_z = 6, 62, 108
    end_x, end_y, end_z  = 60, 70, 144

    for x in filter(lambda x : x % 6 == 0, range(start_x, end_x)):
        for z in filter(lambda z : z % 6 == 0, range(start_z, end_z)):
            for y in range(start_y, end_y):
                res = mcr.command("execute if block %s %s %s minecraft:air run fill %s %s %s %s %s %s minecraft:torch" % (x, y, z, x, y, z, x, y, z))
                if res == "Successfully filled 1 blocks":
                    print(res)
                    break
                res = mcr.command("execute if block %s %s %s minecraft:grass run fill %s %s %s %s %s %s minecraft:torch" % (x, y, z, x, y, z, x, y, z))
                if res == "Successfully filled 1 blocks":
                    print(res)
                    break
Пример #28
0
import time

# TODO Commenting

TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
MC_SERVER_IP = os.getenv('MC_SERVER_IP')
MC_RCON_PORT = os.getenv('MC_RCON_PORT')
MC_RCON_PASS = os.getenv('MC_RCON_PASS')

bot = commands.Bot(command_prefix='!')
difficulty_array = ['easy', 'normal', 'hard']

proposals = list()

mcrcon = MCRcon(str(MC_SERVER_IP), str(MC_RCON_PASS))
mcrcon.connect()
print(mcrcon)
if not mcrcon:
    print('Password incorrect')
    exit(1)

CURRENT_ID = 0


class Proposal():
    def __init__(self, ctx, description='', description_args=[]):
        global CURRENT_ID
        self.id = CURRENT_ID
        CURRENT_ID += 1
        self.ctx = ctx
Пример #29
0
def sound(update, context):
    """Send a message when the command /sound is issued."""
    with MCRcon(mc_server_ip, mc_rcon_password) as mcr:
        resp = mcr.command(
            "/playsound minecraft:entity.villager.ambient voice @a")
Пример #30
0
def web_lock(pl, adress, port, password):
    with MCRcon(adress, password, port=port) as mcr:
        a = mcr.command(
            f"execute at {pl} run fill ~-2 ~-2 ~-2 ~2 ~2 ~2 minecraft:web")
        return a[:12] == 'Successfully'