Giter Club home page Giter Club logo

python-valve's Introduction

Servers.tf

Servers.tf (SVTF for short) is a browser-based server browser for Source games such as Team Fortress 2 and Garry's Mod. The goal is to be able to index servers so that far more sophisticated searches can be made than what is currently possible with the current Source/Steam server browser.

Ideally SVTF will be able to detect mods being ran by the server and be aware of community-made game modes (e.g. Balloon Race or Surfing) so that the user can perform richer searches to find more specific servers.

Developing

The entire SVTF application is encapsulated by a single Python package: serverstf. This package includes all the services needed to get a working SVTF instance.

Install serverstf

Python 3.4 is needed to run SVTF. It's advisable to install the package in editable mode into an isolated environment, e.g. using virtualenv.

$ virtualenv -p $(which python3) env
$ . env/bin/activate
$ pip install -e .[development]

Note that [development] will ensure that development dependencies will also be installed along side core packages. This includes things like Pylint which can be used to check the Python source. Installing these extra packages isn't strictly necessary as long as you're certain you won't need them -- e.g. you're just adding a map image.

Install UI Dependencies

The SVTF user interface is primarily written using CoffeeScript and has a number of external dependencies. These can be installed using npm and bower with Grunt being used to manage compilation of scripts and stylesheets.

In order to scale map images you need to have ImageMagick installed and available on your $PATH. In the following example apt-get is used to install ImageMagick, adapt for your own platform as necessary.

$ apt-get install imagemagick
$ npm install
$ node_modules/.bin/bower install
$ node_modules/.bin/grunt

It is advisable to use the watch Grunt task when actively working on the user interface. Note that watch will not automatically rebuild map images for you as it's quite slow. You can do that manually with the image_resize task.

Run the User Interface

The serverstf package includes a small Pyramid application served via Waitress which runs the UI. As with all SVTF services the UI server can be started by running the serverstf package with a subcommand.

$ python -m serverstf ui 9000
$ xdg-open http://localhost:9000/

Adding Map Images

Map images are displayed in search results and in the server details dialogue. Which image is displayed depends on the map currently in-play by the server. Adding new map images is a relatively simple process; all the configuration lives in serverstf/ui/:

  1. Add the image to images/maps/masters/ in the directory that corresponds to the game the map is used for and with the extension .jpg.
  2. Add appropriate .svtf-map(...) entries to styles/maps.less.
  3. Add or update an entry in data/map-images.yaml.
  4. Run grunt to make sure everything works.

Note that each image must be a JPEG with an aspect ratio of 16:9 and no smaller than 1920x1080. The images should also only contain the map it self. No characters, action or extraneous artefacts which are not native to the map it self (e.g. no blood spatters or bullet holes). In addition to this the image should be more or less completely unaltered; no colour correction.

Exemptions can be made on a case-by-case basis if they can be justified. For example, generic images for game modes.

python-valve's People

Contributors

calinou avatar czbix avatar fantoms avatar fizzadar avatar fuyukai avatar holiverh avatar melbaa avatar necavi avatar nitroflow avatar overfl0 avatar thel3l avatar wastrachan avatar whiteydude avatar yepoleb 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-valve's Issues

A2S_RULES contains binary data for Arma 3 servers

The Arma 3 game uses A2S_RULES entries to store additional data about the server, as described here:
https://community.bistudio.com/wiki/Arma_3_ServerBrowserProtocol2

In short, because some arbitrary (binary) data can be passed in those rules, there is a risk of those rules forming an incorrect UTF-8 string.

How can I best work around the issue of python-vale always trying to decode('utf8') the rules contents without breaking the whole library? (RulesResponse is declared as containing StringFields)
I'd be interested in producing a non-intrusive solution that could then be merged back. I'm not sure that changing the declaration of RulesResponse to contain raw bytestrings a good idea, for example.

  • Python-valve Version(s): 0.2.1

Move class definitions out of __init__.py files

Code in __init__.py is horrible to find, so I suggest we keep it to the absolute minimum. Preferably imports only, but there may be some cases where actual code is necessary. Not a PR, because I want to hear your opinions first.

I need some support

Hey guys I need some support, I am using this code and for some reason whenever I try to do anything with players I get an error

with valve.source.a2s.ServerQuerier(address=("208.103.169.207", 27015)) as server:
    stats = server.info()
    print("{}/{}".format(stats["player_count"], stats["max_players"]))
    for player in server.players()["players"]:
        print(player)

ERROR

Traceback (most recent call last):
  File "C:\Users\maris\PycharmProjects\discord\venv\lib\site-packages\valve\source\messages.py", line 91, in validate
    raise ValueError
ValueError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/maris/PycharmProjects/discord/test.py", line 13, in <module>
    for player in server.players()["players"]:
  File "C:\Users\maris\PycharmProjects\discord\venv\lib\site-packages\valve\source\a2s.py", line 198, in players
    challenge = messages.GetChallengeResponse.decode(self.get_response())
  File "C:\Users\maris\PycharmProjects\discord\venv\lib\site-packages\valve\source\messages.py", line 415, in decode
    values[field.name], buffer = field.decode(buffer, values)
  File "C:\Users\maris\PycharmProjects\discord\venv\lib\site-packages\valve\source\messages.py", line 41, in needs_buffer
    return func(self, buffer, *args, **kwargs)
  File "C:\Users\maris\PycharmProjects\discord\venv\lib\site-packages\valve\source\messages.py", line 131, in decode
    struct.unpack(self.format, field_data)[0]), left_overs)
  File "C:\Users\maris\PycharmProjects\discord\venv\lib\site-packages\valve\source\messages.py", line 95, in validate
    value, self.name))
valve.source.messages.BrokenMessageError: Invalid value (68) for field 'response_type'`

Issue with rust server(s)?

Hi!

I'm testing this on my local rust server and I can't make it work.

Runing

rcon = RCON(address=SERVER_ADDRESS, password=PASSWORD, timeout=1.0)
response = rcon.execute('echo Problems')
rcon.disconnect()

Gives me error:

Traceback (most recent call last):
  File "D:/GIT/bitbucket.com/rustBOTina/src/test.py", line 9, in <module>
    response = rcon.execute('echo Problems')
  File "C:\Python27\lib\site-packages\valve\source\rcon.py", line 272, in execute
    raise AuthenticationError
valve.source.rcon.AuthenticationError

But when I run this:

rcon = RCON(address=SERVER_ADDRESS, password=PASSWORD, timeout=1.0)
rcon.connect()
rcon.authenticate(PASSWORD)
response = rcon.execute('echo Problems')
rcon.disconnect()

I get:

Traceback (most recent call last):
  File "D:/GIT/bitbucket.com/rustBOTina/src/test.py", line 9, in <module>
    response = rcon.execute('echo Problems')
  File "C:\Python27\lib\site-packages\valve\source\rcon.py", line 275, in execute
    with self.response_to(request):
  File "C:\Python27\lib\site-packages\valve\source\rcon.py", line 231, in __enter__
    raise NoResponseError
valve.source.rcon.NoResponseError

But I can see in RUSTY that the command was executed:

Connecting to server
Success
id name time kills deaths suicides player building entity 

id name time kills deaths suicides player building entity 

Problems
Saved 11,340 ents, serialization(0.00), write(0.00), disk(0.00) totalstall(0.01).
Saving complete
Problems
Problems

As you can see I also sent 'stats' command and it printed only header line since no players are connected.

Is this a bug or am I doing something wrong here?

Gevent instead of select()?

Hi,

First of all, awesome project! Thanks!

I was playing with it and find my gevent.monkey.patch_all() does not work, it turns out that a2s.py has its own select() based loop server. Can we create a protocol abstract and make it possible to adapt with non select() event loops?

Add tests

Priority:

  • steam.servers valve.source.messages
  • valve.source.server
  • valve.source.master_server
  • steam.rcon valve.source.rcon
  • steam.id valve.steam.id
  • steam.vdf valve.vdf
  • steam.api valve.steam.api

All tests will use py.test. There should be close to 100% (be sensible when deciding whether to test or not). For things like the servers and rcon there should also be functional tests which run against an actual SRCDS instance.

Implement a canonical representation of a 'server'

As a part of project restructuring (#3) what is currently referred to as steam.servers will be adapted to provide a single point of entry for the user to access all facets of a server.

In practice this means all functionality regarding servers will accessible via a single interface. This will probably be a class (SRCDS or SourceServer?) contained within the steam.servers (due to be renamed) namespace. Everything from searching the master server to the RCON will be exposed here. Various attributes of the server such as player count can be exposed directly as instance properties.

An example of what it may look like:

from valve import source

# List servers from the master server, filtering based on game and region,
# printing out the server's address and name if they have player slots
# available
for server in source.SourceServer.list(game=source.TF2, region=source.EUROPE):
    if server.player_count < server.max_players:
        print(server.address, server.name)

# Perform some automated administration of a server
my_server = source.SourceServer(("gameserver.myhost.com", 27015))
my_server.rcon.authenticate("password")
my_server.rcon.execute("say Performing some admin tasks")
my_server.rcon["some_convar"] = 800

However there are some potential issues I forsee:

Handling a server becoming inaccessible/unavailable after a SourceServer instance is created could be awkward. For example, between you trying to access the player_count and max_players attributes the server might shut down, which would/should raise an exception when an attempt to get the relevant information fails.

This also highlights another issue: do you have to perform a brand new A2S_INFO request each time an attribute is accessed? That could potentially be incredibly inefficient, hitting the server over and over again despite there being no change. Also there's no way to request a specific facet with A2S_INFO which would also mean the vast majority of the response is wasted.

There's no facility available to determine whether your information about a server is up to date so any caching would be have to be 'dumb'. Perhaps a the user can specify a freshness required, which is just a time in seconds indicating how long to wait before requesting the server state. An issue I foresee with this though is that the state may change once an assertion about the state has been made. This makes things like the following fragile.

if server.bot_count > 0:
    do_something_with_nonzero_value(server.bot_count)

A way around this may be to lock the SourceServer instance's state for a short period. But this will probably be kinda ugly IMO, even with context managers:

with server:
    if server.bot_count > 0:
        do_something_with_nonzero_value(server.bot_count)

On an unrelated note. The possible new RCON interface rcon[convar] would mean that the library would have to keep a massive set of records about the various convars ... for which there are a truly ridiculous number. The reason for this is that some convars can be set. Some can't. Some are purely 'NOTIFY' convars. Some expect very particular types of values passed to it. If you want to do anything remotely smart the RCON get/setitem would need to need to be aware of what every convar does.

Alternately you could just have a really lazy implementation. Just assume the user knows what they're doing. Don't bother type checking or anything.

Python2.7

So im pretty sure I read that it works for 2.7 if im wrong im sorry for being a failiure anyways when i run the setup it breaks It prints some stuff closes then when I try to import it in another python file it doesnt work.

Are non-source servers supported? ServerQuerier (Mordhau timeout)

Ive got both source and non-source servers to work but cant get any Mordhau servers to work, Another game I have tried and failed to get any responses from is Warband. They all time out?

Can we only work with source servers and just get lucky on some non-source servers working (like Squad)? Or is something else going on?
For example Squad works fine, which I believe is the same engine as Mordhau (EU4).

Anyone have any ideas how I can get these other game servers working?
Thanks!

  • Python-valve Version(s): 0.2.1
  • Python Version(s): 3.7.3
  • Operating System(s)/Platform(s): win10
  • Game Server(s) and Version(s): Any mordhau / warband server

Code

import valve.source.a2s
SERVER_ADDRESS = ('147.135.6.200', 7779)
with valve.source.a2s.ServerQuerier(SERVER_ADDRESS, timeout=5) as server:
    info = server.info()
    players = server.players()

print("{player_count}/{max_players} {server_name}".format(**info))
for player in sorted(players["players"],
                     key=lambda p: p["score"], reverse=True):
    print("{score} {name}".format(**player)) 

Error

Traceback (most recent call last):
  File "../test.py", line 4, in <module>
    info = server.info()
  File "..\valve\source\a2s.py", line 140, in info
    return messages.InfoResponse.decode(self.get_response())
  File "..\valve\source\a2s.py", line 33, in get_response
    data = valve.source.BaseQuerier.get_response(self)
  File "..\valve\source\__init__.py", line 78, in wrapper
    return function(self, *args, **kwargs)
  File "..\valve\source\__init__.py", line 121, in get_response
    raise NoResponseError("Timed out waiting for response")
valve.source.NoResponseError: Timed out waiting for response

TypeError on ServerQuerier.info()

import valve.source.a2s
import valve.source.master_server

#from valve.source import a2s
#from valve.source import master_server

server = valve.source.a2s.ServerQuerier('162.248.88.218' , 7777)
info = server.info()

Which results in the following error.

 1	Traceback (most recent call last):
 2	  File "query.py", line 8, in <module>
 3	    info = server.info()
 4	  File "/usr/lib/python3.6/site-packages/python_valve-1.0.0-py3.6.egg/valve/source/a2s.py", line 160, in info
 5	  File "/usr/lib/python3.6/site-packages/python_valve-1.0.0-py3.6.egg/valve/source/a2s.py", line 51, in request
 6	TypeError: an integer is required (got type str)

Help would be appreciated.

Improve VDF handling

The current VDF module is an absolute unmaintainable mess. It doesn't have tests, and I have no idea whether it works on all supported Python versions. It pretty much needs to be rewritten.

messages.BrokenMessageError: Invalid value (65) for field 'response_type'

Anytime i try to get the rules for a server i receive this error, all the others (info, players, ping, etc) work fine, but rules always fails with the same error for all servers.
Anyone have any clues?

Edit:
So I don't know why but the game I'm using this with will sometimes reply with another challenge number after sending the previous received challenge number, instead of the rules. The challenge number sometimes is the same and sometimes it's a different one.
For now I've "fixed it" by modifying messages-RulesResponse.decode to check if the response is a challenge response (x41), process the packet through RulesRequest instead, and then in a2s -ServerQuerier - rules added a loop sending another RulesRequest with the new challenge number until the response is an actual rules response (x45)
Probably not the right way to do it?

a2s.py - TypeError: request() takes 2 positional arguments but 3 were given

Just installed python-valve and am trying to get a test running without any errors. I've installed the package using the setup.py file rather than pip to ensure I am running the latest. However, there's an issue when running the simple example from the docs.

Here's the error:

$ python3 test.py 
Traceback (most recent call last):
  File "test.py", line 6, in <module>
    info = server.info()
  File "/usr/local/lib/python3.5/dist-packages/python_valve-0.2.0-py3.5.egg/valve/source/a2s.py", line 138, in info
  File "/usr/local/lib/python3.5/dist-packages/python_valve-0.2.0-py3.5.egg/valve/source/a2s.py", line 28, in request
TypeError: request() takes 2 positional arguments but 3 were given

Vanilla Counter-Strike:Global Offensive server returns invalid value in response_type

An error producing issue was observed after creating 3 brand new CS:GO servers. If host_players_show does not equal 2, responses using the following code are returning a BrokenMessageError exception:

# !/usr/bin/python3.4

import time
import valve.source.a2s

address = ('65.103.35.106', 27015)

while(True):
  try:
      server = valve.source.a2s.ServerQuerier(address)
      info = server.info()
      players = server.players()
      print("{player_count}/{max_players} {server_name}".format(**info))
      for player in sorted(players["players"],
          key=lambda p: p["score"], reverse=True):
              print("{score} {name}".format(**player))
  except valve.source.messages.BrokenMessageError as ErrorMsg:
      print("!******\* Broken server response ********! " , ErrorMsg)
  except valve.source.a2s.NoResponseError:
      print("Server request timed out!")
  time.sleep(1)

Error string from BrokenMessageException:
Invalid value (68) for field 'response_type'

The issue was resolved remotely by setting a host cvar variable on the cs:go server cfg file to allow for "old format" player reporting:
host_players_show 2

To duplicate this error set host_players_show 1

Warning:CS:GO Server by default returns only max players and server uptime. You have to change server cvar "host_players_show" in server.cfg to value "2" if you want to revert to old format with players list

Valve reference: https://developer.valvesoftware.com/wiki/Server_queries#A2S_PLAYER

Project restructuring

The top level namespace will be renamed to valve. From them on each part will be split up in a namespace for the particular Valve product/service they interact with. E.g.

  • valve.steam
  • valve.steam.api
  • valve.steam.client
  • valve.steam.id
  • valve.source

Despite the fact that VDF is technically a part of Source, this will go in the top level namespace as valve.vdf. Items used throughout various Valve product/services will also go here. valve.steam.id is a potential candidate for this as well, but a decision will be made closer to the time.

UDP Support

I like to use python-valve to connect to Battleye in combination with ARMA3 dedicated server and ran into "ConnectionRefusedError". Tried to go through the code and realized you open the socket as TCP explicit.
Don't know when the changed it, but ARMA supports only UDP connection for RCON.

Tried to establish connection via UDP but my knowledge about sockets is so lowlevel^^

Documentation

There is okayish docstring coverage but it could be much better.

Sphinx is the way to go. Perhaps take a look at hooking it up to readthedocs as well. Ideally the documentation should cover everything with a few examples of intended usage patterns.

Switch message decoding from declarative to imperative syntax

I tried implementing the extra data fields in the A2S_INFO response today and wasn't satisfied with how it went. I spent a lot of time scrolling around, trying to figure out how the code works and how to implement the new conditional fields. After like 2 hours I came up with this approach, which is not well implemented and quite ugly in my opinion: Yepoleb@e8a65c4.

Because I wasn't at all satisfied with this, I tried a different approach. I've had a small custom ByteReader class laying around from previous projects and used that to re-implement the InfoResponse decoding. It took around 10 minutes of almost zero effort programming, the extra fields making up about 2 minutes. There's some basic error handling missing, but the decoding part looks nice and clean to me. Here's that code: Yepoleb@ee8b97c

I think the main benefit of declarative programming, which is saving you from writing the same basic function calls over and over, doesn't come into play here. Message classes are only either encoded or decoded, so all we're left with is the massive overhead of the abstractions. Imperative syntax on the other hand is very flexible and straight forward, because all the logic is contained in a single method.

What do you think? I'm willing to do all the rewriting if this suggestion gets accepted, so only worry about future changes.

always getting No module named rcon

hello,

nothing seems to work here, tried python2 or python3 by changing environment variable.
always getting

Traceback (most recent call last):
File "./bla.py", line 2, in
from valve.source.rcon import RCON
ImportError: No module named rcon

any ideas?

valve.source.messages.BufferExhaustedError: No string terminator

Hi guys, I try to get data from the Atlas server (www.playatlas.com). Their map are divided in node and each node is a server with an ip address and a port (3 port for 1 address). I got an error message when I try to get the players present on a server when they are more than 80-90 players.

Traceback (most recent call last):
  File "/opt/mysite/venv/lib/python3.6/site-packages/valve/source/messages.py", line 285, in decode
    entry = self.element.decode(buffer)
  File "/opt/mysite/venv/lib/python3.6/site-packages/valve/source/messages.py", line 423, in decode
    values[field.name], buffer = field.decode(buffer, values)
  File "/opt/mysite/venv/lib/python3.6/site-packages/valve/source/messages.py", line 41, in needs_buffer
    return func(self, buffer, *args, **kwargs)
  File "/opt/mysite/venv/lib/python3.6/site-packages/valve/source/messages.py", line 152, in decode
    raise BufferExhaustedError("No string terminator")
valve.source.messages.BufferExhaustedError: No string terminator

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
  File "/opt/mysite/venv/lib/python3.6/site-packages/valve/source/a2s.py", line 200, in players
    return messages.PlayersResponse.decode(self.get_response())
  File "/opt/mysite/venv/lib/python3.6/site-packages/valve/source/messages.py", line 423, in decode
    values[field.name], buffer = field.decode(buffer, values)
  File "/opt/mysite/venv/lib/python3.6/site-packages/valve/source/messages.py", line 295, in decode
    raise BrokenMessageError(exc)
valve.source.messages.BrokenMessageError: No string terminator

I don't understand why my code does not work, I see some tracker for Atlas on the net that does not have the same problem as me and get the data (https://atlas.hgn.hu/ for example)

  • Python-valve Version(s): 0.2.1
  • Python Version(s): 3.6.7
  • Operating System(s)/Platform(s): Linux Ubuntu 18.04 LTS and Armbian 5.69 Ubunutu 18.04.1 LTS

To test the problem here a little snippet :

with a2s.ServerQuerier(('server_addr', port)) as s:
    print(s.players())

All EU PvP server list and prot are in the attached file, it's a json format, you can see on https://atlas.hgn.hu/grid/eu/pvp for a node with 90+ player and try it yourself with the corresponding address and port ni the attached file.

eu_pvp_server_dict.txt

Feel free to ask me anything if you need more informations or if I missed something.

installing the libary

$ python setup.py install

Returns

$ error: package directory 'steam' does not exist

Had to rename python-valve/valve

to

python/steam

Rewrite steam.api to use requests instead of urllib/urllib2

The whole Steam API implementation is bad and needs to be redone. The big downside of rewriting it to use requests is that it introduces the first third-party dependency which I am trying to avoid. The primary upside is that you get to use requests. :)

The new implementation will have to be far more concrete. Currently it's too abstract. The code is extremely contrived yet it fails to provide any additional functionality beyond basic fetch resource and parse it. It makes dealing with the responses really ... uncool.

The first thing the new implementation will do is completely forget about VDF and XML formats. JSON is nice and works adequately. Additionally, beyond a simple json.loads() of the response, further work can be done to make the responses easier to manage. For example, if an end-point returns a bunch of Steam IDs, then those should be wrapped in actual SteamID instances.

One part I'd especially like to focus on is comma-separated values. Both requests and responses use CSV values. From the user's perspective these should be lists.

Add support for GoldSrc responses

Example: doc
Error at info = server.info()

Traceback (most recent call last):
  File "./test.py", line 9, in <module>
    info = server.info()
  File "/home/kruglov/.virtualenvs/py-valve/local/lib/python2.7/site-packages/valve/source/a2s.py", line 156, in info
    return messages.InfoResponse.decode(self.get_response())
  File "/home/kruglov/.virtualenvs/py-valve/local/lib/python2.7/site-packages/valve/source/messages.py", line 415, in decode
    values[field.name], buffer = field.decode(buffer, values)
  File "/home/kruglov/.virtualenvs/py-valve/local/lib/python2.7/site-packages/valve/source/messages.py", line 41, in needs_buffer
    return func(self, buffer, *args, **kwargs)
  File "/home/kruglov/.virtualenvs/py-valve/local/lib/python2.7/site-packages/valve/source/messages.py", line 131, in decode
    struct.unpack(self.format, field_data)[0]), left_overs)
  File "/home/kruglov/.virtualenvs/py-valve/local/lib/python2.7/site-packages/valve/source/messages.py", line 95, in validate
    value, self.name))
valve.source.messages.BrokenMessageError: Invalid value (109) for field 'response_type'

IndexError: list index out of range

Python 2.7 on Windows.
Attempting to use RCON and I get this error output:

C:\Users\Administrator\Desktop\steamcmd>python r.py
Traceback (most recent call last):
File "r.py", line 6, in
with RCON(SERVER_ADDRESS, PASSWORD) as rcon:
File "build\bdist.win32\egg\valve\source\rcon.py", line 126, in enter
File "build\bdist.win32\egg\valve\source\rcon.py", line 250, in authenticate
File "build\bdist.win32\egg\valve\source\rcon.py", line 226, in enter
File "build\bdist.win32\egg\valve\source\rcon.py", line 199, in process
IndexError: list index out of range

My script is basically just your example with my server info filled in.

from valve.source.rcon import RCON

SERVER_ADDRESS = ("127.0.0.1", 32330)
PASSWORD = "SNIP"

with RCON(SERVER_ADDRESS, PASSWORD) as rcon:
print(rcon("listplayers"))

A2S Ping broken by typo

The Ping function in valve.source.a2s has a typo that causes the following error:
NameError: name 'monontic' is not defined

This typo is on line 68 in the following code:
time_sent = monontic.monotonic()

It appears that monotonic was accidentally typed as monontic

  • Python-valve Version(s): 0.2.1
  • Python Version(s): 3.7.2
  • Operating System(s)/Platform(s): Windows
  • Game Server(s) and Version(s): Space Engineers

Proxy

Can someone tell me how can i use this lib with proxy?

rcon against local ark server times out

I'm actually just learning Python. I'm trying out different things with python-valve.

Basically, just copy/pasted this and adjusted it for my own server from this page:
https://python-valve.readthedocs.io/en/latest/rcon.html

#!/usr/bin/python

import valve.rcon

address = ("1.2.3.4", 27020)
password = "myadminpassword"

with valve.rcon.RCON(address, password, timeout=30) as rcon:
    response = rcon.execute("broadcast Hello, world!")
    print(response.text)

The firewall on my server is open, I can telnet to the RCON port (specified on the command line and in the game ini file.

I am using battlemetrics.com using the same port on the public IP address (forwarded from the router) which just works.

When I change the port to the incorrect port, I immediately get a 'connection refused'. When I change the IP address, it never connects. When I change the password to be incorrect, it actually tells me the password is wrong.

It connects, authenticates, but the command is never executed.

Any ideas please?

Thanks.

Future of this project?

I was wondering - what is the path that python-valve is taking? Do we have a roadmap? With potential features? Might be worth looking at adding it to the projects tab :]

ImportError: No module named server

I'm not much of a python wiz, so excuse me if this is some trivial or stupid user error, but I just cannot get the examples to work.

I'm running debian 7 and I've cloned the git repo and used

sudo python setup.py install

to install this. Python version is 2.7.3. The install doesn't seem to give any errors, but still just taking any example from the wiki and trying to run it, it doesn't seem to be able to find the module.

TF2 server returning fragments with the compressed flag, but the fragments aren't compressed?

I'm using a slighty older edited version of python-valve, but I just checked and most of the code is still the same. I've found a TF2 server, that returns a large RULES list, which is split up in fragments. The fragments however, are not compressed, although the most significant bit of the fragment ID is 1.

gameserver: 190.0.164.209:27025

My code changes:
Added to messages.py:

class FirstFragment(Message):

    fields = (
        LongField("message_id"),
        ByteField("fragment_count"),
        ByteField("fragment_id"),  # 0-indexed
        ShortField("mtu"),
        LongField("total_size"), # total size of all the compressed fragments
    )

    @property
    def is_compressed(self):
        return bool(self["message_id"] & 2**(2*8))

Changed in a2s.py:

        if response["split"] == messages.SPLIT:
            fragments = {}
            fragment = messages.FirstFragment.decode(response.payload)
            if fragment.is_compressed:
                raise NotImplementedError("Fragments are compressed")
            fragments[fragment["fragment_id"]] = fragment
            while len(fragments) < fragment["fragment_count"]:
                data = BaseServerQuerier.get_response(self)
                fragment = messages.Fragment.decode(
                    messages.Header.decode(data).payload)
                fragments[fragment["fragment_id"]] = fragment
            merged_fragments = b"".join([frag[1].payload for frag in
                            sorted(fragments.items(), key=lambda f: f[0])])

            response_type = merged_fragments[0]
            rules_count = merged_fragments[1]
            rule_list = merged_fragments[2:]

            merged_msg = b"".join([bytes([response_type]), bytes([rules_count]), rule_list])

            # Return merged payload frame
            return merged_msg

I essentially only changed the first fragment to a version which includes the total_size header to make it work. But once I uncomment the fragment check, the code fails. Any ideas on what is going on here? I couldn't find anything about it in the documentation.

Improve RCON message body decoding

#13 highlighted a case where the body of an RCON message (a response to a status command to be specific) may not be valid ASCII.

This is contrary to the Valve wiki page for RCON which seems to imply that RCON message bodies should be null terminated ASCII encoded strings. Evidently this isn't always the case. As I was unable to recreate the issue for my self I can't really dig into it much further to know what encoding srcds is actually using. Perhaps its some kind of "extended ASCII", e.g. ISO 8859-1? Maybe it's UTF-8. Who knows, but I don't think we should simply guess.

2d56e64 was added as a workaround for #13 but this is not ideal as it simply ignores anything it can't decode.

Looking at the two other Python RCON implementations (SourceLib and pysrcds) neither of them seem to even attempt to decode the message body, leaving it as a bytestring. Whilst no confident assertions can be made about the encoding of RCON messages there is merit to this behavior IMO.

Ultimately:

  • UnicodeDecodeError should never be propagated from Message.decode.
  • ASCII should be assumed until the actual encoding can be determined.
  • Message should expose the message body as a bytestring along side the Unicode body so that if there is any data loss from ignoring decode errors the user at least has a chance of salvaging the real message body by handling the decoding themselves or by just using the bytestring bodies exclusively.

๐ŸŽฑ

under linux low unique servers, mostly duplicates

import valve.source.a2s
import valve.source.master_server
s=set()
msq = valve.source.master_server.MasterServerQuerier()
try:
    for address in msq.find(
            gamedir=u"7dtd"):
        s.add(address)
        print len(s)
except valve.source.a2s.NoResponseError:
    print "Master server request timed out!"

~4600 unique on windows
~ 670 unique on linux

7 days to die (7dtd) player names empty

index always 0, score always 0 too

players = server.get_players()
for player in players['players']:
    print player.items()
[(u'duration', 3707.952880859375), (u'index', 0), (u'score', 0), (u'name', u'')]
[(u'duration', 3146.773193359375), (u'index', 0), (u'score', 0), (u'name', u'')]
[(u'duration', 2702.712158203125), (u'index', 0), (u'score', 0), (u'name', u'')]
[(u'duration', 2188.73193359375), (u'index', 0), (u'score', 0), (u'name', u'')]
[(u'duration', 1989.33203125), (u'index', 0), (u'score', 0), (u'name', u'')]
[(u'duration', 1640.9486083984375), (u'index', 0), (u'score', 0), (u'name', u'')]
[(u'duration', 1288.8568115234375), (u'index', 0), (u'score', 0), (u'name', u'')]
[(u'duration', 1080.558349609375), (u'index', 0), (u'score', 0), (u'name', u'')]
[(u'duration', 1063.529541015625), (u'index', 0), (u'score', 0), (u'name', u'')]
[(u'duration', 1037.4505615234375), (u'index', 0), (u'score', 0), (u'name', u'')]
[(u'duration', 1037.064453125), (u'index', 0), (u'score', 0), (u'name', u'')]
[(u'duration', 1030.4398193359375), (u'index', 0), (u'score', 0), (u'name', u'')]
[(u'duration', 1029.0120849609375), (u'index', 0), (u'score', 0), (u'name', u'')]
[(u'duration', 927.1685791015625), (u'index', 0), (u'score', 0), (u'name', u'')]
[(u'duration', 831.4614868164062), (u'index', 0), (u'score', 0), (u'name', u'')]
[(u'duration', 287.7505798339844), (u'index', 0), (u'score', 0), (u'name', u'')]

Add additional maintainer(s)

There are still a lot of unmerged forks and it would be nice to have a complete upstream branch again. As you apparently don't have the time to maintain this properly, I suggest you add other people who are willing to take care of the project.

Sending a RCON "status" command with no players in the server causes UnicodeDecodeError

I'm not sure exactly what causes this, but when doing rcon("status") with no human players in the server, I get the following error:

File "...\source\rcon.py", line 176, in process
    self._read_buffer += self._socket.recv(4096)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 4: ordinal not in range(128)

Having bots connected to the server does not fix this.

player_count incorrect and blank player names

I'm querying a CSGO server and the returned player_count is incorrect through both get_info() and get_players(). get_players()['players'] gets the players in the server, but also gets a number of players with blank names. If these blank names are removed from player_count, it's correct. Any idea of what's going on here?

Add support for EDF

I'm trying to use this for Rust and I think the field I'm after ("gametags") is an extra data field.

Arma III timeout

I'm getting a timeout while looking up Arma III servers.

python-valve version: 0.2.1
python version 3.5.3 and 3.6.3

Tested on Debian and Arch using this code https://gist.github.com/Cightline/12c6def0bddce9bb3a88335895f809c1

One test was on my local machine, the other was on a VPS.

Here is the output:

Looking up servers...
Oslund
Wisconsinites United [Private]
The Mess Around Server
Buddhatao Resurrected
Beard's Operational Training Server
RDP - Liberation
Serbedzija
[BR] SNIPERS SEALS TEAM - HARDCORE - em MANUTENCAO
Asylum #4 : Altis Life | HOUSING | PERM GANGS | TERRITORY | Vig
Krakk a Lakkin
8th Marine Battalion Private Operation
3rd Infantry Division Realism Server |ts.3rdinf.us
3rd Infantry Division Training Server |ts.3rdinf.us
S&W Liberation
Take2
3rd Infantry Division Public Server |ts.3rdinf.us
Exile Subsistence - Thirsk Remastered (64 Bit)
DEFKON Gaming WL Test Server
[JAC] ALiVE | NATO Invasion
DEFKON Gaming | Tanoa W-Land | Powered by GoServerzone | Day | 
DEFKON-G Tanoa|Exile|FullMilitarized|PVE/PVP|100KStart|Revive
DEFKON Gaming Exile Test Server
Stray Rounds' Dedicated Server
Raven Sword Corporation
The Breakfast Club Arma3 Server
Nodgaming.com - King Of The Hill - US #1 - Infantry | InitialSe
CGS ArmA III Server
ZG Gaming Altis Life v5.0(1.80)
TFAthens.com - King Of The Hill โ€“ Infantry | InitialServers.c
[DTG] DoubleTapGamer.com - King Of The Hill - US Infantry 24/7 
Test Exile - hosted @ InitialServers.com
TeamExclusive - King Of The Hill 24/7 Day - Infantry | InitialS
[US]Fazed and Confused Exile
Insurgency - hosted @ InitialServers.com
Optixhosting,net
ZRArmy.com - D1 - Dallas,TX USA
FlufyBuny's ARMA 3 Server
_BiB_ Arma3 Server-CA-US#3
 [COOP] TFT8.com | US Public
Clan ArgA ARGENTINA - www.clanarga.com.ar
Blackwater Realism Unit // Operations Server ACE
=AVRW= Advanced Virtual Warfare Server
Exception: Timed out waiting for response

@vin173 has mentioned that Bohemia Interactive changed their protocol, I'm not sure what that would mean to you guys.

Here are a couple links from BI:
https://community.bistudio.com/wiki/STEAMWORKSquery
https://community.bistudio.com/wiki/Arma_3_ServerBrowserProtocol2

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.