Skip to content

Instantly share code, notes, and snippets.

@ip2k
Created January 25, 2024 22:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ip2k/e7aaf66b4204110ef513ec006832c9ee to your computer and use it in GitHub Desktop.
Save ip2k/e7aaf66b4204110ef513ec006832c9ee to your computer and use it in GitHub Desktop.
post-server-status.py
# -*- coding: utf-8 -*-
import valve.rcon
import requests
import json
import re
import http.client as http_client
# TODO update /home/tf2server/.local/lib/python3.6/site-packages/valve/rcon.py to set encoding=utf-8 so this will work
# CONFIG
min_players = 3 # min players to trigger a status post
max_players = 31 # max players to trigger a status post
http_client.HTTPConnection.debuglevel = 1
webhook_url = "https://discordapp.com/api/webhooks/xxxxx/xxxxx" #webhook webhook_url, from here: https://i.imgur.com/aT3AThK.png
server_address = ("xxx.xxx.xxx.xxx", 27015)
password = "CHANGE_ME"
# Functions
def parse_status(status=''):
lines=status.split('\n')
ret = {
'hostname': lines[0].split(':')[1].strip(),
'ip': f'{lines[2].split(":")[1].strip()}:27015',
'map': lines[5].split(' ')[6],
'numplayers': lines[7].split(' ')[2],
'players': [re.findall(r'"(.+)"', line) for line in lines[10:-1]]
}
return ret
def post_to_discord(status={}):
data = {}
data["username"] = "ChanclaBot"
#for all params, see https://discordapp.com/developers/docs/resources/webhook#execute-webhook
data["content"] = f'''**Join Now**: steam://connect/{status['ip']}
**Map**: {status['map']}
**Players**: {status['numplayers']}/32
'''
data["embeds"] = []
embed = {}
embed['description'] = ''
#for all params, see https://discordapp.com/developers/docs/resources/channel#embed-object
for player in status['players']:
embed['description'] += f'{player[0].strip()}\n'
#embed["description"] = status['players']
embed["title"] = "Current Players"
data["embeds"].append(embed)
result = requests.post(webhook_url, data=json.dumps(data), headers={"Content-Type": "application/json"})
try:
result.raise_for_status()
except requests.exceptions.HTTPError as err:
print(err)
return False
else:
print("Payload delivered successfully, code {}.".format(result.status_code))
return True
# Main
if __name__ == "__main__":
with valve.rcon.RCON(server_address, password) as rcon:
rcon_resp = rcon('status')
# import pdb; pdb.set_trace()
# rcon_clean = rcon_resp.body.decode('utf-8', 'ignore')
# status = parse_status(rcon_clean)
status = parse_status(rcon_resp)
print(status)
if min_players <= int(status['numplayers']) <= max_players: # only post update if we're between min and max players
post_to_discord(status)
else:
print(f'Not enough players to post status. Current players:{status["numplayers"]} required: {min_players}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment