Coder Social home page Coder Social logo

mcipc's Introduction

Documentation Status

mcipc

A Minecraft inter-process communication API implementing the RCON and Query protocols.

News

2020-12-21 - mcipc-2.0

Great news: mcipc is now available in version 2. The version 2 update includes the outsourcing of the RCON protocol and client implementation into an own project. This allowes for the RCON library to be used independently of mcipc, e.g. for other games which support the RCON protocol. Furthermore mcipc's RCON client implementations have been overhauled. They now provide functions to interact with the respective server. It was therefor necessary to not have one implementation of mcipc.rcon.Client, but three:

  • mcipc.rcon.be.Client Client for Bedrock Edition servers.
  • mcipc.rcon.ee.Client Client for Education Edition servers.
  • mcipc.rcon.je.Client Client for Java Edition servers.

To provide some backwards compatibility, the mcipc.rcon.Client is now an alias for mcipc.rcon.je.Client. You'll find a full documentation of each client's capabilities, i.e. methods in the documentation.

Requirements

mcipc requires Python 3.9 or higher. It also depends on rcon which has been split from this project. If you install mcicp via pip, it will automatically be installed as a dependency.

Documentation

Documentation is available on readthedocs.

Quick start

Install mcipc from the AUR or via:

pip install mcipc

Query protocol

The Query protcol is used to query a Minecraft server for server information. The Minecraft query protocol has two query modes: basic stats and full stats.

from mcipc.query import Client

with Client('127.0.0.1', 25565) as client:
    basic_stats = client.stats()            # Get basic stats.
    full_stats = client.stats(full=True)    # Get full stats.

print(basic_stats)
print(full_stats)

RCON protocol

The RCON protocol is used to remotely control a Minecraft server, i.e. execute commands on a Minecraft server and receive the respective results.

from mcipc.rcon.je import Biome, Client     # For Java Edition servers.
#from mcipc.rcon.be import Client           # For Bedrock Edition servers.
#from mcipc.rcon.ee import Client           # For Education Edition servers.

with Client('127.0.0.1', 5000, passwd='mysecretpassword') as client:
    seed = client.seed                              # Get the server's seed.
    players = client.list()                         # Get the server's players info.
    mansion = client.locate('mansion')              # Get the next mansion's location.
    badlands = client.locatebiome(Biome.BADLANDS)   # Get the next location of a badlands biome.

print(seed)
print(players)
print(mansion)
print(badlands)

Example output of the above commands with a Java Edition client:

-8217057902979500137
Players(online=1, max=20, players=[Player(name='coNQP', uuid=None, state=None)])
Location(name='mansion', x=-7216, y=None, z=-1952, distance=7479)
Location(name='minecraft:badlands', x=1512, y=None, z=3388, distance=3634)

Credits

Many thanks to all contributers to the Minecraft Wiki and the Wiki.vg.

License

Copyright (C) 2018-2021 Richard Neumann

mcipc is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

mcipc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with mcipc. If not, see http://www.gnu.org/licenses/.

Legal

Minecraft content and materials are trademarks and copyrights of Mojang and its licensors. All rights reserved. This program is free software and is not affiliated with Mojang.

mcipc's People

Contributors

conqp avatar gilesknap avatar jaredneil avatar n6udp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

mcipc's Issues

I can't run the example program

Hey, I can't run this program

from mcipc.rcon.je import Biome, Client     # For Java Edition servers.

with Client('127.0.0.1', 5000, passwd='mysecretpassword') as client:
    seed = client.seed                              # Get the server's seed.
    players = client.list()                         # Get the server's players info.
    mansion = client.locate('mansion')              # Get the next mansion's location.
    badlands = client.locatebiome(Biome.BADLANDS)   # Get the next location of a badlands biome.

print(seed)
print(players)
print(mansion)
print(badlands)

I have on the vps Python 3.9.0+ and the package mcipc and I have this error. I don't understand what needs to be changed

File "/root/python/rcon.py", line 1, in <module>
    from mcipc.rcon.je import Biome, Client     # For Java Edition servers.
  File "/usr/local/lib/python3.9/dist-packages/mcipc/rcon/__init__.py", line 3, in <module>
    from mcipc.rcon.be import Client as BedrockClient
  File "/usr/local/lib/python3.9/dist-packages/mcipc/rcon/be/__init__.py", line 3, in <module>
    from mcipc.rcon.be.client import Client
  File "/usr/local/lib/python3.9/dist-packages/mcipc/rcon/be/client.py", line 3, in <module>
    from mcipc.rcon.be.commands.ability import ability
  File "/usr/local/lib/python3.9/dist-packages/mcipc/rcon/be/commands/ability.py", line 3, in <module>
    from mcipc.rcon.client import Client
  File "/usr/local/lib/python3.9/dist-packages/mcipc/rcon/client.py", line 3, in <module>
    from rcon import Client
  File "/root/python/rcon.py", line 1, in <module>
    from mcipc.rcon.je import Biome, Client     # For Java Edition servers.
  File "/usr/local/lib/python3.9/dist-packages/mcipc/rcon/je/__init__.py", line 3, in <module>
    from mcipc.rcon.je.client import Client
  File "/usr/local/lib/python3.9/dist-packages/mcipc/rcon/je/client.py", line 3, in <module>
    from mcipc.rcon.client import Client
ImportError: cannot import name 'Client' from partially initialized module 'mcipc.rcon.client' (most likely due to a circular import) (/usr/local/lib/python3.9/dist-packages/mcipc/rcon/client.py)

Thank you for the help you can give me

Always times out

I want to implement this to my discord bot, but it's always times out. Here is my base:

    @commands.command()
    async def mcstats(self, ctx, *, ip):
        if ctx.author.bot:
            return
        try:
            port = ip.split(":")[1]
        except:
            port = 25565
        ip = ip.split(":")[0]
        with Client(ip, int(port), timeout=10) as client:
            basic_stats = client.basic_stats
        await ctx.send(basic_stats)

Traceback:

Traceback (most recent call last):
  File "/Users/nemetharon/Desktop/FightMan01_bot/1.2.3/sql/fun.py", line 1504, in mcstats
    with Client(ip, int(port), timeout=10) as client:
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mcipc/query/client.py", line 30, in __enter__
    self._challenge_token = self.handshake().challenge_token
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mcipc/query/proto/handshake.py", line 64, in handshake
    return self.communicate(request, Response)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mcipc/query/client.py", line 49, in communicate
    response = self._recv_all(buffer=buffer)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mcipc/query/client.py", line 44, in _recv_all
    return b''.join(self._recv_chunks(buffer=buffer))
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mcipc/query/client.py", line 36, in _recv_chunks
    while chunk := self._socket.recv(buffer):
socket.timeout: timed out

Changes to behaviour of Item

In the latest version of mcipc there have been some changes to behaviour of Item.

I could fix my code to work with the new behaviour but I'd like to understand if these are intentional.

# pip install mcipc==2.3.8 rcon==2.2.1

In [2]: str(Item.AIR)
Out[2]: 'minecraft:air'

In [3]: Item("minecraft:air")
ValueError: 'minecraft:air' is not a valid Item

In [4]: Item("air")
Out[4]: <Item.AIR: 'air'>

#pip install mcipc==2.4.0 rcon==2.3.1

In [2]: str(Item.AIR)
Out[2]: 'Item.AIR'

In [3]: Item("minecraft:air")
Out[3]: <Item.AIR: 'minecraft:air'>

In [4]: Item("air")
ValueError: 'air' is not a valid Item

[An Request] Add Whitelist

How would i check if a server is whitelisted or not MCPE maybe for mcjava as well if it is similar.
If you could add that feature it would be great! thx

TypeError: cannot convert 'NoneType' object to bytes

Hello, I am trying to call stats() but I am getting this error.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\James\AppData\Local\Programs\Python\Python39\lib\site-packages\mcipc\query\client.py", line 97, in stats
    file.write(bytes(request))
  File "C:\Users\James\AppData\Local\Programs\Python\Python39\lib\site-packages\mcipc\query\proto\basic_stats.py", line 33, in __bytes__
    payload += bytes(self.challenge_token)
TypeError: cannot convert 'NoneType' object to bytes

If it helps, I am trying to pull information from mc.hypixel.net.
Any help would be appreciated.

Orientation of Profile in mktunnel

This is a subtle issue and may be intended behaviour but I found it confusing to use. It you agree that this behaviour should be changed I will look into the implementation and submit a PR.

When you use the TOP_LEFT anchor in mktunnel the profile of the tunnel on screen looking North looks like the profile does in code.

e.g.

    p: Profile = [
        [Item.RED_WOOL.value, Item.AIR.value, Item.GREEN_WOOL.value],
        [Item.AIR.value, Item.AIR.value, Item.AIR.value],
        [Item.BLUE_WOOL.value, Item.AIR.value, Item.YELLOW_WOOL.value],
    ]

produces a red square in the top left.

However, if you use other anchors the result is that your profile is rotated about the TOP left or [0,0] in the profile lists.
I would have expected a translation only so that your profile still looks the same.

I guess it is useful to be able to rotate the profile, but would prefer a separate function to do so.

By example this image shows the above profile sent in all compas points. The left is TOP_LEFT and right is BOTTOM_RIGHT.
image

Error while attempting to run a command using RCON on a Minecraft Bedrock Server

Hi, so I am currently in the process of attempting to use RCON to run some commands remotely to my Minecraft Bedrock Server, however I am getting some errrors. I am using a discord.py Discord Bot to connect to the RCON and remotely send the command. However, I am getting one of two errors:
1st Error:
Error: connect() got an unexpected keyword argument 'login'
2nd Error:
Error: BaseClient.init() takes 3 positional arguments but 4 were given

My code is pretty standard as I am trying to make a simple unmute command in game which has been coded onto the RCON seperately.
My code is as below. If you could please help me in potentially informing me with the issue to fix that would be more than appreciated. Thank you. Sorry if I am missing something clear, this is my first time using the library.
discord.py code (Python):

@tree.command(guild = discord.Object(servers), name = 'unmute', description='A command to unmute a user on the Server (ingame)') 
@app_commands.checks.cooldown(2, 15, key = lambda i: (i.guild_id, i.user.id))
@app_commands.describe(username = "The user you want to unmute on the server.")
#@app_commands.default_permissions(administrator = True)
async def unmute(interaction: discord.Interaction, username: str):
    ip = "thisserver.net"
    port = 15342
    password = "MyRCONPW"
    
    try:
        with Client(ip, port) as client:
            client.login(password)
            command = f"unmute {username}"
            response = client.run(command)
            await interaction.response.send_message(f"Unmuted: {response}")
    except Exception as e:
        await interaction.response.send_message("An error occurred while sending the command.")
        print(f"Error: {e}")

list with colors returns Invalid Paper string

It seems like colors is whats causing the problem
When trying to return a list of players I get the following message:

Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 85, in wrapped ret = await coro(*args, **kwargs) File "/python/Big Brain Bot/cogs/minecraft.py", line 69, in mcserver response = client.list().encode("ISO-8859_1") File "/usr/local/lib/python3.8/dist-packages/mcipc/rcon/functions.py", line 56, in inner return parser(function(*args, **kwargs)) File "/usr/local/lib/python3.8/dist-packages/mcipc/rcon/response_types/players.py", line 103, in parse return from_paper(match) File "/usr/local/lib/python3.8/dist-packages/mcipc/rcon/response_types/players.py", line 93, in from_paper return Players(int(online), int(max_), list(players)) File "/usr/local/lib/python3.8/dist-packages/mcipc/rcon/response_types/players.py", line 75, in players_from_paper_names yield player_from_paper_name(name) File "/usr/local/lib/python3.8/dist-packages/mcipc/rcon/response_types/players.py", line 65, in player_from_paper_name raise ValueError(f'Invalid Paper server string: {name}') ValueError: Invalid Paper server string: §6username§r:

script:
with Client("ip", port, passwd="passwd") as client: response = client.list()

ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

When running this code:

from mcipc.rcon.je import Biome, Client     # For Java Edition servers.
#from mcipc.rcon.be import Client           # For Bedrock Edition servers.
#from mcipc.rcon.ee import Client           # For Education Edition servers.

with Client('127.0.0.1', 25575, passwd='7894') as client:
    seed = client.seed                              # Get the server's seed.
    players = client.list()                         # Get the server's players info.
    mansion = client.locate('mansion')              # Get the next mansion's location.
    badlands = client.locatebiome(Biome.BADLANDS)   # Get the next location of a badlands biome.

print(seed)
print(players)
print(mansion)
print(badlands)

Even after turning off the firewall I get: ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it. What am I doing wrong?

Circular import error

Hello, when I try to import java rcon client like this:

from mcipc.rcon.je import Client

The following error occurs:

Traceback (most recent call last):
  File "C:\Users\bmaru\Desktop\rcon.py", line 1, in <module>
    from mcipc.rcon.je import client
  File "D:\Programs\Python3.11.0\Lib\site-packages\mcipc\rcon\__init__.py", line 3, in <module>
    from mcipc.rcon.be import Client as BedrockClient
  File "D:\Programs\Python3.11.0\Lib\site-packages\mcipc\rcon\be\__init__.py", line 3, in <module>
    from mcipc.rcon.be.client import Client
  File "D:\Programs\Python3.11.0\Lib\site-packages\mcipc\rcon\be\client.py", line 3, in <module>
    from mcipc.rcon.be.commands.ability import ability
  File "D:\Programs\Python3.11.0\Lib\site-packages\mcipc\rcon\be\commands\ability.py", line 5, in <module>
    from mcipc.rcon.client import Client
  File "D:\Programs\Python3.11.0\Lib\site-packages\mcipc\rcon\client.py", line 3, in <module>
    from rcon import source
  File "C:\Users\bmaru\Desktop\rcon.py", line 1, in <module>
    from mcipc.rcon.je import client
  File "D:\Programs\Python3.11.0\Lib\site-packages\mcipc\rcon\je\__init__.py", line 3, in <module>
    from mcipc.rcon.je.client import Client
  File "D:\Programs\Python3.11.0\Lib\site-packages\mcipc\rcon\je\client.py", line 3, in <module>
    from mcipc.rcon.client import Client as _Client
ImportError: cannot import name 'Client' from partially initialized module 'mcipc.rcon.client' (most likely due to a circular import) (D:\Programs\Python3.11.0\Lib\site-packages\mcipc\rcon\client.py)

Python 3.11.0 and mcipc 2.4.2

Converting into dict()

I cant convert the output of Full/Basic stats into json, What am i doing wrong?

try:
      from mcipc.query.client import Client
      import socket
      
      with Client("mc.mc.nl", 5000, timeout=1.0) as mcser:
          return dict(mcser.stats(full=True))

except socket.timeout as timeout:
      return False 

except:
      return False

this returns:

  File "c:\Users\***\Desktop\website\main.py", line 43, in <module>
    print(dict(stats))
TypeError: cannot convert dictionary update sequence element #0 to a sequence

An existing connection was forcibly closed by the remote host

I am trying to get mcipc communicating with a vanilla minecraft server.

When running the example program for mcipc I get an [WinError 10054] An existing connection was forcibly closed by the remote host error however I dont experience any errors when using rcon directly.

This is the example mcipc program I am using:

from mcipc.query import Client

with Client('127.0.0.1', 25565) as client:
    basic_stats = client.stats()            # Get basic stats.
    full_stats = client.stats(full=True)    # Get full stats.

print(basic_stats)
print(full_stats)

.. which generates this error and I dont see any notifications in the server console.

Traceback (most recent call last):
  File "C:\Users\marti\Documents\martinohanlon\rcon-test-env\rcontests\mcipc-test.py", line 3, in <module>
    with Client('127.0.0.1', 25565) as client:
  File "C:\Users\marti\Documents\martinohanlon\rcon-test-env\lib\site-packages\mcipc\query\client.py", line 59, in __enter__
    self.connect()
  File "C:\Users\marti\Documents\martinohanlon\rcon-test-env\lib\site-packages\mcipc\query\client.py", line 50, in connect
    self.challenge_token = self.handshake()
  File "C:\Users\marti\Documents\martinohanlon\rcon-test-env\lib\site-packages\mcipc\query\client.py", line 97, in handshake
    response = Response.read(file)
  File "C:\Users\marti\Documents\martinohanlon\rcon-test-env\lib\site-packages\mcipc\query\proto\handshake.py", line 47, in read
    type_ = Type.read(file)
  File "C:\Users\marti\Documents\martinohanlon\rcon-test-env\lib\site-packages\mcipc\query\proto\common.py", line 101, in read
    return cls.from_bytes(file.read(1))
  File "C:\Users\marti\AppData\Local\Programs\Python\Python310\lib\socket.py", line 705, in readinto
    return self._sock.recv_into(b)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

I created a simple program using rcon to check everything was running correctly.

from rcon.source import Client

with Client('127.0.0.1', 25575, passwd='letme1n') as client:
    response = client.run('say', 'hi')

print(response)

... which runs without error and generates the following result in the server console.

[15:18:58] [RCON Listener #1/INFO]: Thread RCON Client /127.0.0.1 started
[15:18:58] [Server thread/INFO]: [Not Secure] [Rcon] hi
[15:18:58] [RCON Client /127.0.0.1 #2/INFO]: Thread RCON Client /127.0.0.1 shutting down

I didnt know if there was a way of specifying the password for mcipc? but as far as I can tell the connection is being made anyway?!

Any advice would be greatly received.

client.players error

Hey. Thats the code I use right now.

from mcipc.rcon import Client


with Client('myip', myport) as client:
    client.login('mypass')
    players = client.players
    mansion = client.locate('Mansion')
    print(players)
    print(mansion)

AttributeError: 'NoneType' object has no attribute 'groups'
Thats the error i get everytime.
Any ideas? Thanks!

support for use outside of a context

It would be useful to support use without a context

e.g.

client =  Client("localhost", 25701, passwd="x")
client.fill(bounds.start, bounds.end, "air", FillMode.REPLACE)
client.close()

This makes it easy to use client in an ipython session which is very useful for experimentation. (I have got around this by calling _enter_ manually)

Block States in Item

I think I'd like to extend the type ITEM to include block states, so that it could for example translate to

minecraft:acacia_button[face=up, facing=north, powered=true]

Do you think this is sensible?

Long responses from commands are truncated and break the connection

This is a java edition 1.19.2 server and the latest version of mcipc.

Here is an example sequence of commands that demonstrate the issue. The response gets truncated at 4096 bytes and the connection stops working.

In [2]: c.seed
Out[2]: 0

In [3]: c.data.get(entity="TransformerScorn", path="Health")
Out[3]: 'TransformerScorn has the following entity data: 20.0f'

In [4]: c.data.get(entity="TransformerScorn")
Out[4]: 'TransformerScorn has the following entity data: {Brain: {memories: {}}, HurtByTimestamp: 0, SleepTimer: 0s, Attributes: [{Base: 0.10000000149011612d, Name: "minecraft:generic.movement_speed"}], Invulnerable: 0b, FallFlying: 0b, PortalCooldown: 0, AbsorptionAmount: 0.0f, abilities: {invulnerable: 1b, mayfly: 1b, instabuild: 1b, walkSpeed: 0.1f, mayBuild: 1b, flying: 0b, flySpeed: 0.05f}, FallDistance: 0.0f, recipeBook: {recipes: ["minecraft:chest", "minecraft:gray_stained_glass", "minecraft:wooden_pickaxe", "minecraft:charcoal", "minecraft:stone_hoe", "minecraft:smooth_sandstone", "minecraft:oak_stairs", "minecraft:stone_button", "minecraft:stonecutter", "minecraft:stone_pickaxe", "minecraft:glass_pane", "minecraft:cobbled_deepslate_slab", "minecraft:cobbled_deepslate_slab_from_cobbled_deepslate_stonecutting", "minecraft:brown_stained_glass", "minecraft:wooden_axe", "minecraft:glass_bottle", "minecraft:deepslate_bricks_from_cobbled_deepslate_stonecutting", "minecraft:oak_fence_gate", "minecraft:stripped_oak_wood", "minecraft:purple_stained_glass", "minecraft:red_stained_glass", "minecraft:deepslate_brick_stairs_from_cobbled_deepslate_stonecutting", "minecraft:soul_campfire", "minecraft:ladder", "minecraft:cut_sandstone_from_sandstone_stonecutting", "minecraft:stone_stairs_from_stone_stonecutting", "minecraft:crafting_table", "minecraft:stone_stairs", "minecraft:sandstone_stairs_from_sandstone_stonecutting", "minecraft:sandstone_wall", "minecraft:dark_oak_wood", "minecraft:blue_stained_glass", "minecraft:oak_fence", "minecraft:stone_slab_from_stone_stonecutting", "minecraft:magenta_stained_glass", "minecraft:chiseled_deepslate_from_cobbled_deepslate_stonecutting", "minecraft:stone_brick_slab_from_stone_stonecutting", "minecraft:stick", "minecraft:oak_sign", "minecraft:furnace", "minecraft:stone_slab", "minecraft:oak_trapdoor", "minecraft:sandstone_wall_from_sandstone_stonecutting", "minecraft:cobbled_deepslate_wall_from_cobbled_deepslate_stonecutting", "minecraft:polished_deepslate_from_cobbled_deepslate_stonecutting", "minecraft:oak_door", "minecraft:stone_axe", "minecraft:deepslate", "minecraft:barrel", "minecraft:wooden_sword", "minecraft:oak_planks", "minecraft:stone_brick_stairs_from_stone_stonecutting", "minecraft:yellow_stained_glass", "minecraft:crossbow", "minecraft:green_stained_glass", "minecraft:light_blue_stained_glass", "minecraft:chiseled_stone_bricks_stone_from_stonecutting", "minecraft:stone_bricks", "minecraft:sandstone_slab_from_sandstone_stonecutting", "minecraft:deepslate_tile_wall_from_cobbled_deepslate_stonecutting", "minecraft:wooden_shovel", "minecraft:cobbled_deepslate_wall", "minecraft:cut_sandstone", "minecraft:cobbled_deepslate_stairs", "minecraft:chiseled_sandstone_from_sandstone_stonecutting", "minecraft:light_gray_stained_glass", "minecraft:orange_stained_glass", "minecraft:smooth_stone", "minecraft:polished_deepslate_slab_from_cobbled_deepslate_stonecutting", "minecraft:birch_planks", "minecraft:stone_shovel", "minecraft:pink_stained_glass", "minecraft:dark_oak_planks", "minecraft:deepslate_tiles_from_cobbled_deepslate_stonecutting", "minecraft:white_stained_glass", "minecraft:oak_button", "minecraft:wooden_hoe", "minecraft:cobbled_deepslate_stairs_from_cobbled_deepslate_stonecutting", "minecraft:cyan_stained_glass", "minecraft:stone_pressure_plate", "minecraft:polished_deepslate_stairs_from_cobbled_deepslate_stonecutting", "minecraft:oak_pressure_plate", "minecraft:campfire", "minecraft:sandstone_slab", "minecraft:stone_sword", "minecraft:polished_deepslate_wall_from_cobbled_deepslate_stonecutting", "minecraft:deepslate_brick_wall_from_cobbled_deepslate_stonecutting", "minecraft:packed_mud", "minecraft:deepslate_tile_slab_from_cobbled_deepslate_stonecutting", "minecraft:sandstone_stairs", "minecraft:deepslate_brick_slab_from_cobbled_deepslate_stonecutting", "minecraft:oak_slab", "minecraft:lime_stained_glass", "minecraft:cut_sandstone_slab_from_sandstone_stonecutting", "minecraft:deepslate_tile_stairs_from_cobbled_deepslate_stonecutting", "minecraft:stone_brick_walls_from_stone_stonecuttin'

In [5]: c.data.get(entity="TransformerScorn", path="Health")
ERROR:  SessionTimeout: 

In [6]: c.seed
ERROR:  ValueError: 979659040 is not a valid Type

In [7]: c.data.get(entity="TransformerScorn", path="Health")
ERROR:  SessionTimeout: 

In [8]: 

Cant figure out how to read chat

hey, it seems like it should be possible to use rcon to read the chat, but i cant figure out any methods that allow this.

ive looked in the code, would i be correct to assume that its not implemented?

[query] full_stats throws OverflowError

Ignoring exception in on_command_error
Traceback (most recent call last):
  File "C:\Users\prave\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\prave\Desktop\Codest\Python\MSC\SerenityBot.py", line 280, in mctest2
    full_stats = client.full_stats
  File "C:\Users\prave\AppData\Local\Programs\Python\Python38-32\lib\site-packages\mcipc\query\proto\full_stats.py", line 177, in full_stats
    return self.communicate(request, FullStats)
  File "C:\Users\prave\AppData\Local\Programs\Python\Python38-32\lib\site-packages\mcipc\query\client.py", line 48, in communicate  
    self._socket.send(bytes(packet))
  File "C:\Users\prave\AppData\Local\Programs\Python\Python38-32\lib\site-packages\mcipc\query\proto\full_stats.py", line 107, in __bytes__
    payload += self.challenge_token.to_bytes(4, 'big')
OverflowError: can't convert negative int to unsigned

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\prave\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 312, in _run_event      
    await coro(*args, **kwargs)
  File "c:\Users\prave\Desktop\Codest\Python\MSC\SerenityBot.py", line 50, in on_command_error
    raise error
  File "C:\Users\prave\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\prave\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\prave\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OverflowError: can't convert negative int to unsigned
@bot.command()
async def mctest2(ctx):
    with Client(ip, port) as client:
        full_stats = client.full_stats
    await ctx.send(full_stats)

Fix this issue please, i like this lib, basic_stats working fine but not this one

Doesn't work anymore

The module doesn't work on wind 10 or ubuntu, it always gives me timeout error. On websites dedicated to this link["mcstats.io"] it works.

Python 3.8

Replit has not changed to Python 3.9. Is there any way for me to use this on there?

Parsing NBT

I'm opening this issue to discuss NBT parsing.

(I note that NBTs are a Java edition feature and I'm not familiar with how similar information is handled in other editions)

I have implemented a simple deserializer for Stringified Named Binary Tag data which is the format returned by commands like data get

# extract preamble from string responses to commands (benign for raw SNBT)
preamble_re = re.compile(r"[^\[{]*(.*)")
# extract list type identifiers
list_types_re = re.compile(r"[LBI];")
# regex to extract all unquoted items
unquoted_re = re.compile(r'([-.A-Za-z0-9]+)(?=([^"]*"[^"]*")*[^"]*$)')
# regex to extract numeric values
integers_re = re.compile(r'"(\d+)[bsl]?"')
no_decimal_floats_re = re.compile(r'"([0-9]+)[fd]"')
floats_re = re.compile(r'"(\d+.\d+)[fd]"')


def parse_nbt(snbt_text: str) -> object:
    """
    Naive deserialization of an SNBT string into a object graph of Python types.

    Note that this is one way only since the following details are lost:
    - distinction between byte, short, int long, types (suffixes of b,s,none,l)
    - distinction between float, double types (suffixes of f,d)
    - distinction between SNBT and raw JSON (enclosed in single quotes)

    See https://minecraft.fandom.com/wiki/NBT_format
    """
    text = preamble_re.sub(r"\1", snbt_text)
    text = list_types_re.sub(r"", text)
    text = unquoted_re.sub(r'"\1"', text).replace("'", "")
    text = no_decimal_floats_re.sub(r"\1.0", text)
    text = floats_re.sub(r"\1", text)
    text = integers_re.sub(r"\1", text)
    text = text.replace('"true"', '"True"').replace('"false"', '"False"')

    return json.loads(text)

I'm not sure the above approach is worthy of the nicely typed mcipc library.

There is a lot more work to do to make a serializable NBT class in python. A useful NBT class would need to:

  • represent all of the numeric types that are not native to python
  • support arithmetic with python floats/int
  • represent pure JSON attributes (so they can be enclosed in single quotes on serialise)
  • support dot notation for accessing child nodes

This would mean you could do something like this:

# increase the number of items in slot 0 of the chest at 626, 73, -1654
nbt = client.data.get(block=Vec3(626, 73, -1654)) 
nbt.Items[0].Count += 10
client.data.merge(block=Vec3(626, 73, -1654), nbt)

So is this worth implementing? The nbt serialize would be limited to the following commands that I can think of:

  • data merge
  • summon
  • These commands when used with a block entity
    • setblock
    • give
    • fill

Wheras the dumb deserialize specified above is useful for querying information about Players, Mobs, Entities, Block Entities etc.

Linux Bug

Every time i use mcipc on ubuntu:

from mcipc.query import Client 

def test(ip, Qport):
    with Client(str(ip), int(Qport), timeout=1) as s:
        stat = s.stats(full=True)
        print(stat)

test("The Ip Address", "The Qport")

I get this error:

Traceback (most recent call last):
  File "/home/###/Desktop/server/client.py", line 9, in <module>
    test()
  File "/home/###/Desktop/server/client.py", line 4, in test
    with Client("###", ###, timeout=1) as s:
  File "/home/###/.local/lib/python3.9/site-packages/mcipc/query/client.py", line 59, in __enter__
    self.connect()
  File "/home/###/.local/lib/python3.9/site-packages/mcipc/query/client.py", line 51, in connect
    self.challenge_token = self.handshake()
  File "/home/###/.local/lib/python3.9/site-packages/mcipc/query/client.py", line 87, in handshake
    response = Response.read(file)
  File "/usr/local/lib/python3.9/typing.py", line 693, in __getattr__
    return getattr(self.__origin__, attr)
AttributeError: '_SpecialForm' object has no attribute 'read'

But this doesn't happend on windows 10 (pro).. Python instal is 3.9

ConnectionRefusedError: [Errno 111] Connection refused

`from mcipc.rcon import Client

with Client(...) as client:
client.login(...)
print(client.seed)
client.run('day')`

Traceback (most recent call last):
File "/home/RnCraft/test.py", line 4, in
with Client('95.216.62.176', 29675) as client:
File "/home/RnCraft/.local/lib/python3.8/site-packages/mcipc/common.py", line 23, in enter
self.connect()
File "/home/RnCraft/.local/lib/python3.8/site-packages/mcipc/common.py", line 39, in connect
return self._socket.connect(self.socket)
ConnectionRefusedError: [Errno 111] Connection refused

Bedrock?

I am totally confused on this. I see you have put a lot of work into setting up functions for Bedrock Edition. I can't for the life of me find anything on the Internet about getting it working and I added the Java commands and they also don't seem to work. Sorry I'm opening an issue just would love to use this if it exists.

Query exception when server-ip is 'localhost'

If you setup a local server with server-ip=localhost in server.properties (127.0.0.1 does not give an error), the 'full_stats' and 'basic_stats' functions will result in an exception. Wanted to ask if there are any future plans to add support for using localhost and domains in general? Could even just make it an argument for the Client classes to specify that it's not an IP.

is async supporting?

I'm need async's functions. Your project supports async? xD
I'm not English so sorry for my English

mcipc.rcon.exceptions.InvalidPacketStructure:

from mcipc.rcon import Client

with Client('127.0.0.1', 25565) as client:

    client.say('oi')

whenever I try to give some input it returns this error:
mcipc.rcon.exceptions.InvalidPacketStructure: ('Invalid tail.', b'')

I'm having problems creating the code

I can't understand what I did wrong. :(

import discord
import mcipc.query
import asyncio
import time
from discord.ext import commands, tasks
from key import token

intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix='!', intents=intents)
TOKEN = token.get("TOKEN")

@client.event
async def on_ready():
print(f'{client.user} estΓ‘ online!')

voice_channels = client.guilds[0].voice_channels
channel1 = next((vc for vc in voice_channels if vc.name == "Servidor Minecraft"), None)
channel2 = next((vc for vc in voice_channels if vc.name == "Jogadores Online"), None)

if not channel1:
    category = client.guilds[0].categories[0]
    channel1 = await category.create_voice_channel("Servidor Minecraft")

if not channel2:
    category = client.guilds[0].categories[0]
    channel2 = await category.create_voice_channel("Jogadores Online")

client.loop.create_task(update_status(channel1, channel2))

async def update_status(channel1, channel2):
while True:
try:
host, port = "###.enxada.host", #####
with mcipc.query.Client(host, port) as client:
status = client.full_stat()

        online_players = status['players']['online']
        max_players = status['players']['max']

        await channel1.edit(name=f"🟒 Servidor Online: {online_players}/{max_players}")
        await channel2.edit(name=f"🟒 {online_players}/{max_players} Jogadores Online")

    except Exception as e:
        # Em caso de erro, mostrar mensagem no console
        print(f"Erro ao atualizar status do servidor: {e}")

    # Esperar 10 minutos antes de atualizar novamente
    await asyncio.sleep(600)

@client.command()
async def status(ctx):
await ctx.send("Adicionado Status do servidor")

@client.command()
async def ping(ctx):
await ctx.send('Pong! {0}'.format(round(bot.latency, 1)))

client.run(TOKEN)

2.2.6 and Fillmode

Upgrading to 2.2.6 causes me to see the following when calling the fill command with a Fillmode of REPLACE.

Traceback (most recent call last):
  File "main.py", line 34, in <module>
    setup(client)
  File "main.py", line 18, in setup
    client.fill(bounds.start, bounds.end, "air", FillMode.REPLACE)  # type: ignore
  File "/usr/lib/python3.8/typing.py", line 759, in __getattr__
    return getattr(self.__origin__, attr)
AttributeError: '_SpecialForm' object has no attribute 'REPLACE'

Downgrading to 2.2.5 restores correct operation.

Timeout support

Thanks for the library, works great. I'm using it for a script that will automatically spin down the VPS the minecraft server is running on if no players are detected within a certain time.

However one issue I'm finding is if the server is not responding then the library blocks indefinitely. I'm using the following code to fetch the stats.

from mcipc.query import Client

with Client(host, port) as client:
        basic_stats = client.basic_stats

It would be nice if some optional timeout could be implemented into the client so that e.g. server being offline could be handled better.

TypeError: 'TypeVar' object is not callable

Hello. Thanks for the great library.
I tried to use this library, but encountered the following error when importing the module.

from mcipc.rcon.je import Client
  File "/Users/***/.anyenv/envs/pyenv/versions/3.10.2/lib/python3.10/site-packages/mcipc/rcon/proxy.py", line 28, in CommandProxy
    def _proxy(self, cls: DelegatedType, *args: str) -> DelegatedType():
TypeError: 'TypeVar' object is not callable

I reverted the commit e0be7a6, relying on the error message, and the error no longer occurred.

I am not familiar with Python, so maybe I am doing something else wrong.

I would appreciate it if you could check.

Thank you very much.

Can use the run command...

I've been trying to use run(command), but when ever I do, nothin happens. Things like client.players work fine tho...
This is my Code:


from mcipc.rcon import Client

ip="*"
port=25575
password="
"
command="/op MeviOfDoom"
with Client(ip, port) as client:
client.login(password)
client.run(command)
players = client.players

print(players)

(I've been using client.players as check, if the connection works fine.)
I tried to put in the command without and with the / and I tried both of that while I used it directly where the variable command sits right now. I also tried with and without "" in client.run, even tho I couldnt see why it would work without... I'm probably just stupid and used something wrong or something like that, so I'm sorry but still thank you for your help :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.