Code Monkey home page Code Monkey logo

rs2wapy's Introduction

rs2wapy

Travis Maintainability

Rising Storm 2: Vietnam WebAdmin Python Interface

Provides a Python interface for performing RS2 WebAdmin tasks programmatically.

The library uses PycURL internally to communicate with RS2 WebAdmin.

Work in progress; interface will change!

Brief Usage Examples

This section contains some brief usage examples. For more comprehensive tutorials check out the examples repository.

Installation
# Requires Python=>3.7
pip install rs2wapy
Steam Web API key (optional)

Setting your Steam Web API key as an environment variable allows rs2wapy to offer some extra functionality.

Unix:

export STEAM_WEB_API_KEY="TOPSECRETKEY"

Windows:

set STEAM_WEB_API_KEY="TOPSECRETKEY"
Quickstart

It is recommended to create a new WebAdmin account for rs2wapy.

from rs2wapy import RS2WebAdmin

wa = RS2WebAdmin(
    username="AutoModerator",
    password="topsecret123",
    webadmin_url="http://localhost:8080/",
)
Poll server ranked status and switch map automatically
while True:
    if not wa.get_current_game().ranked:
        wa.post_chat_message("Unranked bug happened! Changing map in 5 seconds!")
        time.sleep(5)
        wa.change_map("VNTE-Resort")
    time.sleep(1)
Forward in-game chat to a Discord webhook with discord.py.
import time

from discord import RequestsWebhookAdapter
from discord import Webhook
from discord.utils import escape_markdown
from discord.utils import escape_mentions

from rs2wapy import RS2WebAdmin
from rs2wapy.models import AllTeam
from rs2wapy.models import BlueTeam
from rs2wapy.models import RedTeam

# Discord webhook info.
webhook = Webhook.partial(
    id=123456,
    token="abcdefg",
    adapter=RequestsWebhookAdapter()
)

# Webadmin credentials.
USERNAME = "Admin"
PASSWORD = "adminpassword"
URL = "http://127.0.0.1:8080/ServerAdmin"

TEAM_TO_EMOJI = {
    BlueTeam: ":blue_square:",
    RedTeam: ":red_square:",
    AllTeam: ":white_square_button:",
}

TEAM_TO_TEAMNAME = {
    BlueTeam: "SOUTH",
    RedTeam: "NORTH",
    AllTeam: "ALL",
}


def get_team_emoji(team):
    try:
        return TEAM_TO_EMOJI[team]
    except KeyError:
        return "?"


def get_team_name(team):
    try:
        return TEAM_TO_TEAMNAME[team]
    except KeyError:
        return "?"


def main():
    webadmin = RS2WebAdmin(USERNAME, PASSWORD, URL)
    messages = []

    while True:
        try:
            messages.extend(webadmin.get_chat_messages())
        except Exception as e:
            print(f"error getting messages: {e}")
            print("attempting to reconnect...")
            webadmin = RS2WebAdmin(USERNAME, PASSWORD, URL)

        if messages:
            for message in messages:
                text = message.text
                sender = message.sender
                team = message.team

                team_name = get_team_name(team)
                team_emoji = get_team_emoji(team)

                # Prevent pinging @everyone from in-game chat
                # and other "funny" stuff.
                text = escape_markdown(text)
                text = escape_mentions(text)
                sender = escape_markdown(sender)
                sender = escape_mentions(sender)

                try:
                    webhook.send(f"**{sender}** [{team_name}] {team_emoji}: {text}")
                except Exception as e:
                    print(f"error sending message: {e}")

        messages = []
        time.sleep(3)

The above are just simple examples of how to use the library. In the future, the library will be able to automate all tasks which RS2 WebAdmin offers. You can check the status of currently implemented WebAdmin features here: #9.

rs2wapy's People

Contributors

tuokri avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

covak sgnconnects

rs2wapy's Issues

Log WebAdmin return message after performing a request

When performing a request, the response content from WebAdmin contains the following element:

<div class="message info">
MESSAGE_FROM_WEB_ADMIN
</div>

MESSAGE_FROM_WEB_ADMIN contains informational or error messages.
Logging this response value would be beneficial for debugging.

Implement async chat message fetching

To avoid "missing" chat messages, store them in a queue.
The messages are put to the queue in the background.
Calling get_chat_messages will get the messages from the message queue.

Test with mypy

Type annotations are used extensively in the project. Testing them with mypy would be beneficial.

Implement all RS2 WebAdmin features

This list mirrors the RS2 WebAdmin side panel.

  • Current Game
  • Change Map
  • Chat
  • Players
  • Squads
  • Workshop Tool
  • Management Console
  • Members
  • Banned IDs
  • Session Bans
  • Toxic Players
  • Tracking
  • Settings
  • Campaign
  • Gametypes
  • Map Cycles
  • Mutators
  • Server Actors
  • WebAdmin
  • Administrators

Refactor duplicates related to _perform calls

This following boilerplate appears multiple times.

headers = self._make_chat_headers()
postfields = "ajax=1"
c = pycurl.Curl()
_set_postfields(c, postfields)
resp = self._perform(self._chat_data_url, curl_obj=c, headers=headers)

Refactor it by adding an optional postfields parameter to _perform.

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.