├── .gitattributes ├── .github └── FUNDING.yml ├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.md ├── __init__.py ├── bec_rcon.py ├── example └── api_example.py ├── requirements.txt └── setup.py /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | custom: https://paypal.me/TeamYoshiE 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .nox/ 42 | .coverage 43 | .coverage.* 44 | .cache 45 | nosetests.xml 46 | coverage.xml 47 | *.cover 48 | .hypothesis/ 49 | .pytest_cache/ 50 | 51 | # Translations 52 | *.mo 53 | *.pot 54 | 55 | # Django stuff: 56 | *.log 57 | local_settings.py 58 | db.sqlite3 59 | 60 | # Flask stuff: 61 | instance/ 62 | .webassets-cache 63 | 64 | # Scrapy stuff: 65 | .scrapy 66 | 67 | # Sphinx documentation 68 | docs/_build/ 69 | 70 | # PyBuilder 71 | target/ 72 | 73 | # Jupyter Notebook 74 | .ipynb_checkpoints 75 | 76 | # IPython 77 | profile_default/ 78 | ipython_config.py 79 | 80 | # pyenv 81 | .python-version 82 | 83 | # celery beat schedule file 84 | celerybeat-schedule 85 | 86 | # SageMath parsed files 87 | *.sage.py 88 | 89 | # Environments 90 | .env 91 | .venv 92 | env/ 93 | venv/ 94 | ENV/ 95 | env.bak/ 96 | venv.bak/ 97 | 98 | # Spyder project settings 99 | .spyderproject 100 | .spyproject 101 | 102 | # Rope project settings 103 | .ropeproject 104 | 105 | # mkdocs documentation 106 | /site 107 | 108 | # mypy 109 | .mypy_cache/ 110 | .dmypy.json 111 | dmypy.json 112 | 113 | # Pyre type checker 114 | .pyre/ 115 | example/api_example_secret.py -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution-NonCommercial-ShareAlike 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More_considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International 58 | Public License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-NonCommercial-ShareAlike 4.0 International Public License 63 | ("Public License"). To the extent this Public License may be 64 | interpreted as a contract, You are granted the Licensed Rights in 65 | consideration of Your acceptance of these terms and conditions, and the 66 | Licensor grants You such rights in consideration of benefits the 67 | Licensor receives from making the Licensed Material available under 68 | these terms and conditions. 69 | 70 | 71 | Section 1 -- Definitions. 72 | 73 | a. Adapted Material means material subject to Copyright and Similar 74 | Rights that is derived from or based upon the Licensed Material 75 | and in which the Licensed Material is translated, altered, 76 | arranged, transformed, or otherwise modified in a manner requiring 77 | permission under the Copyright and Similar Rights held by the 78 | Licensor. For purposes of this Public License, where the Licensed 79 | Material is a musical work, performance, or sound recording, 80 | Adapted Material is always produced where the Licensed Material is 81 | synched in timed relation with a moving image. 82 | 83 | b. Adapter's License means the license You apply to Your Copyright 84 | and Similar Rights in Your contributions to Adapted Material in 85 | accordance with the terms and conditions of this Public License. 86 | 87 | c. BY-NC-SA Compatible License means a license listed at 88 | creativecommons.org/compatiblelicenses, approved by Creative 89 | Commons as essentially the equivalent of this Public License. 90 | 91 | d. Copyright and Similar Rights means copyright and/or similar rights 92 | closely related to copyright including, without limitation, 93 | performance, broadcast, sound recording, and Sui Generis Database 94 | Rights, without regard to how the rights are labeled or 95 | categorized. For purposes of this Public License, the rights 96 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 97 | Rights. 98 | 99 | e. Effective Technological Measures means those measures that, in the 100 | absence of proper authority, may not be circumvented under laws 101 | fulfilling obligations under Article 11 of the WIPO Copyright 102 | Treaty adopted on December 20, 1996, and/or similar international 103 | agreements. 104 | 105 | f. Exceptions and Limitations means fair use, fair dealing, and/or 106 | any other exception or limitation to Copyright and Similar Rights 107 | that applies to Your use of the Licensed Material. 108 | 109 | g. License Elements means the license attributes listed in the name 110 | of a Creative Commons Public License. The License Elements of this 111 | Public License are Attribution, NonCommercial, and ShareAlike. 112 | 113 | h. Licensed Material means the artistic or literary work, database, 114 | or other material to which the Licensor applied this Public 115 | License. 116 | 117 | i. Licensed Rights means the rights granted to You subject to the 118 | terms and conditions of this Public License, which are limited to 119 | all Copyright and Similar Rights that apply to Your use of the 120 | Licensed Material and that the Licensor has authority to license. 121 | 122 | j. Licensor means the individual(s) or entity(ies) granting rights 123 | under this Public License. 124 | 125 | k. NonCommercial means not primarily intended for or directed towards 126 | commercial advantage or monetary compensation. For purposes of 127 | this Public License, the exchange of the Licensed Material for 128 | other material subject to Copyright and Similar Rights by digital 129 | file-sharing or similar means is NonCommercial provided there is 130 | no payment of monetary compensation in connection with the 131 | exchange. 132 | 133 | l. Share means to provide material to the public by any means or 134 | process that requires permission under the Licensed Rights, such 135 | as reproduction, public display, public performance, distribution, 136 | dissemination, communication, or importation, and to make material 137 | available to the public including in ways that members of the 138 | public may access the material from a place and at a time 139 | individually chosen by them. 140 | 141 | m. Sui Generis Database Rights means rights other than copyright 142 | resulting from Directive 96/9/EC of the European Parliament and of 143 | the Council of 11 March 1996 on the legal protection of databases, 144 | as amended and/or succeeded, as well as other essentially 145 | equivalent rights anywhere in the world. 146 | 147 | n. You means the individual or entity exercising the Licensed Rights 148 | under this Public License. Your has a corresponding meaning. 149 | 150 | 151 | Section 2 -- Scope. 152 | 153 | a. License grant. 154 | 155 | 1. Subject to the terms and conditions of this Public License, 156 | the Licensor hereby grants You a worldwide, royalty-free, 157 | non-sublicensable, non-exclusive, irrevocable license to 158 | exercise the Licensed Rights in the Licensed Material to: 159 | 160 | a. reproduce and Share the Licensed Material, in whole or 161 | in part, for NonCommercial purposes only; and 162 | 163 | b. produce, reproduce, and Share Adapted Material for 164 | NonCommercial purposes only. 165 | 166 | 2. Exceptions and Limitations. For the avoidance of doubt, where 167 | Exceptions and Limitations apply to Your use, this Public 168 | License does not apply, and You do not need to comply with 169 | its terms and conditions. 170 | 171 | 3. Term. The term of this Public License is specified in Section 172 | 6(a). 173 | 174 | 4. Media and formats; technical modifications allowed. The 175 | Licensor authorizes You to exercise the Licensed Rights in 176 | all media and formats whether now known or hereafter created, 177 | and to make technical modifications necessary to do so. The 178 | Licensor waives and/or agrees not to assert any right or 179 | authority to forbid You from making technical modifications 180 | necessary to exercise the Licensed Rights, including 181 | technical modifications necessary to circumvent Effective 182 | Technological Measures. For purposes of this Public License, 183 | simply making modifications authorized by this Section 2(a) 184 | (4) never produces Adapted Material. 185 | 186 | 5. Downstream recipients. 187 | 188 | a. Offer from the Licensor -- Licensed Material. Every 189 | recipient of the Licensed Material automatically 190 | receives an offer from the Licensor to exercise the 191 | Licensed Rights under the terms and conditions of this 192 | Public License. 193 | 194 | b. Additional offer from the Licensor -- Adapted Material. 195 | Every recipient of Adapted Material from You 196 | automatically receives an offer from the Licensor to 197 | exercise the Licensed Rights in the Adapted Material 198 | under the conditions of the Adapter's License You apply. 199 | 200 | c. No downstream restrictions. You may not offer or impose 201 | any additional or different terms or conditions on, or 202 | apply any Effective Technological Measures to, the 203 | Licensed Material if doing so restricts exercise of the 204 | Licensed Rights by any recipient of the Licensed 205 | Material. 206 | 207 | 6. No endorsement. Nothing in this Public License constitutes or 208 | may be construed as permission to assert or imply that You 209 | are, or that Your use of the Licensed Material is, connected 210 | with, or sponsored, endorsed, or granted official status by, 211 | the Licensor or others designated to receive attribution as 212 | provided in Section 3(a)(1)(A)(i). 213 | 214 | b. Other rights. 215 | 216 | 1. Moral rights, such as the right of integrity, are not 217 | licensed under this Public License, nor are publicity, 218 | privacy, and/or other similar personality rights; however, to 219 | the extent possible, the Licensor waives and/or agrees not to 220 | assert any such rights held by the Licensor to the limited 221 | extent necessary to allow You to exercise the Licensed 222 | Rights, but not otherwise. 223 | 224 | 2. Patent and trademark rights are not licensed under this 225 | Public License. 226 | 227 | 3. To the extent possible, the Licensor waives any right to 228 | collect royalties from You for the exercise of the Licensed 229 | Rights, whether directly or through a collecting society 230 | under any voluntary or waivable statutory or compulsory 231 | licensing scheme. In all other cases the Licensor expressly 232 | reserves any right to collect such royalties, including when 233 | the Licensed Material is used other than for NonCommercial 234 | purposes. 235 | 236 | 237 | Section 3 -- License Conditions. 238 | 239 | Your exercise of the Licensed Rights is expressly made subject to the 240 | following conditions. 241 | 242 | a. Attribution. 243 | 244 | 1. If You Share the Licensed Material (including in modified 245 | form), You must: 246 | 247 | a. retain the following if it is supplied by the Licensor 248 | with the Licensed Material: 249 | 250 | i. identification of the creator(s) of the Licensed 251 | Material and any others designated to receive 252 | attribution, in any reasonable manner requested by 253 | the Licensor (including by pseudonym if 254 | designated); 255 | 256 | ii. a copyright notice; 257 | 258 | iii. a notice that refers to this Public License; 259 | 260 | iv. a notice that refers to the disclaimer of 261 | warranties; 262 | 263 | v. a URI or hyperlink to the Licensed Material to the 264 | extent reasonably practicable; 265 | 266 | b. indicate if You modified the Licensed Material and 267 | retain an indication of any previous modifications; and 268 | 269 | c. indicate the Licensed Material is licensed under this 270 | Public License, and include the text of, or the URI or 271 | hyperlink to, this Public License. 272 | 273 | 2. You may satisfy the conditions in Section 3(a)(1) in any 274 | reasonable manner based on the medium, means, and context in 275 | which You Share the Licensed Material. For example, it may be 276 | reasonable to satisfy the conditions by providing a URI or 277 | hyperlink to a resource that includes the required 278 | information. 279 | 3. If requested by the Licensor, You must remove any of the 280 | information required by Section 3(a)(1)(A) to the extent 281 | reasonably practicable. 282 | 283 | b. ShareAlike. 284 | 285 | In addition to the conditions in Section 3(a), if You Share 286 | Adapted Material You produce, the following conditions also apply. 287 | 288 | 1. The Adapter's License You apply must be a Creative Commons 289 | license with the same License Elements, this version or 290 | later, or a BY-NC-SA Compatible License. 291 | 292 | 2. You must include the text of, or the URI or hyperlink to, the 293 | Adapter's License You apply. You may satisfy this condition 294 | in any reasonable manner based on the medium, means, and 295 | context in which You Share Adapted Material. 296 | 297 | 3. You may not offer or impose any additional or different terms 298 | or conditions on, or apply any Effective Technological 299 | Measures to, Adapted Material that restrict exercise of the 300 | rights granted under the Adapter's License You apply. 301 | 302 | 303 | Section 4 -- Sui Generis Database Rights. 304 | 305 | Where the Licensed Rights include Sui Generis Database Rights that 306 | apply to Your use of the Licensed Material: 307 | 308 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 309 | to extract, reuse, reproduce, and Share all or a substantial 310 | portion of the contents of the database for NonCommercial purposes 311 | only; 312 | 313 | b. if You include all or a substantial portion of the database 314 | contents in a database in which You have Sui Generis Database 315 | Rights, then the database in which You have Sui Generis Database 316 | Rights (but not its individual contents) is Adapted Material, 317 | including for purposes of Section 3(b); and 318 | 319 | c. You must comply with the conditions in Section 3(a) if You Share 320 | all or a substantial portion of the contents of the database. 321 | 322 | For the avoidance of doubt, this Section 4 supplements and does not 323 | replace Your obligations under this Public License where the Licensed 324 | Rights include other Copyright and Similar Rights. 325 | 326 | 327 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 328 | 329 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 330 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 331 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 332 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 333 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 334 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 335 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 336 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 337 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 338 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 339 | 340 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 341 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 342 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 343 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 344 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 345 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 346 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 347 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 348 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 349 | 350 | c. The disclaimer of warranties and limitation of liability provided 351 | above shall be interpreted in a manner that, to the extent 352 | possible, most closely approximates an absolute disclaimer and 353 | waiver of all liability. 354 | 355 | 356 | Section 6 -- Term and Termination. 357 | 358 | a. This Public License applies for the term of the Copyright and 359 | Similar Rights licensed here. However, if You fail to comply with 360 | this Public License, then Your rights under this Public License 361 | terminate automatically. 362 | 363 | b. Where Your right to use the Licensed Material has terminated under 364 | Section 6(a), it reinstates: 365 | 366 | 1. automatically as of the date the violation is cured, provided 367 | it is cured within 30 days of Your discovery of the 368 | violation; or 369 | 370 | 2. upon express reinstatement by the Licensor. 371 | 372 | For the avoidance of doubt, this Section 6(b) does not affect any 373 | right the Licensor may have to seek remedies for Your violations 374 | of this Public License. 375 | 376 | c. For the avoidance of doubt, the Licensor may also offer the 377 | Licensed Material under separate terms or conditions or stop 378 | distributing the Licensed Material at any time; however, doing so 379 | will not terminate this Public License. 380 | 381 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 382 | License. 383 | 384 | 385 | Section 7 -- Other Terms and Conditions. 386 | 387 | a. The Licensor shall not be bound by any additional or different 388 | terms or conditions communicated by You unless expressly agreed. 389 | 390 | b. Any arrangements, understandings, or agreements regarding the 391 | Licensed Material not stated herein are separate from and 392 | independent of the terms and conditions of this Public License. 393 | 394 | 395 | Section 8 -- Interpretation. 396 | 397 | a. For the avoidance of doubt, this Public License does not, and 398 | shall not be interpreted to, reduce, limit, restrict, or impose 399 | conditions on any use of the Licensed Material that could lawfully 400 | be made without permission under this Public License. 401 | 402 | b. To the extent possible, if any provision of this Public License is 403 | deemed unenforceable, it shall be automatically reformed to the 404 | minimum extent necessary to make it enforceable. If the provision 405 | cannot be reformed, it shall be severed from this Public License 406 | without affecting the enforceability of the remaining terms and 407 | conditions. 408 | 409 | c. No term or condition of this Public License will be waived and no 410 | failure to comply consented to unless expressly agreed to by the 411 | Licensor. 412 | 413 | d. Nothing in this Public License constitutes or may be interpreted 414 | as a limitation upon, or waiver of, any privileges and immunities 415 | that apply to the Licensor or You, including from the legal 416 | processes of any jurisdiction or authority. 417 | 418 | ======================================================================= 419 | 420 | Creative Commons is not a party to its public licenses. 421 | Notwithstanding, Creative Commons may elect to apply one of its public 422 | licenses to material it publishes and in those instances will be 423 | considered the "Licensor." Except for the limited purpose of indicating 424 | that material is shared under a Creative Commons public license or as 425 | otherwise permitted by the Creative Commons policies published at 426 | creativecommons.org/policies, Creative Commons does not authorize the 427 | use of the trademark "Creative Commons" or any other trademark or logo 428 | of Creative Commons without its prior written consent including, 429 | without limitation, in connection with any unauthorized modifications 430 | to any of its public licenses or any other arrangements, 431 | understandings, or agreements concerning use of licensed material. For 432 | the avoidance of doubt, this paragraph does not form part of the public 433 | licenses. 434 | 435 | Creative Commons may be contacted at creativecommons.org. -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # API and Discord Module for BEC RCon 2 | 3 | # Install 4 | Install via pip: 5 | ``` 6 | pip install git+https://github.com/Yoshi-E/Python-BEC-RCon.git 7 | ``` 8 | Alternatively you can download the python wheel and install it with: 9 | ``` 10 | pip install bec_rcon-0.1.0-py3-none-any.whl 11 | ``` 12 | 13 | # Demo 14 | Check out the full demo in api_example.py. 15 | This short example connects to a RCon server and prints all server messages it receives. 16 | ```python 17 | 18 | def msg(args): 19 | message = args[0] 20 | print(message) 21 | 22 | import bec_rcon 23 | rcon_client = bec_rcon.ARC("192.168.0.1", "MyPassword", 2302) 24 | rcon_client.add_Event("received_ServerMessage", msg) 25 | rcon_client.loadMission("becti_0097_z1305.Altis") #Filename without .pbo! 26 | rcon_client.addBan(player_id=1, reason="Rcon is watching!", time=0) 27 | ``` 28 | # Known Issues: 29 | * [Outbound messages can only contain ASCII charaters](https://github.com/Yoshi-E/Python-BEC-RCon/issues/1) 30 | * [During mission load RCon can lose connection] This is intended behavior. 31 | 32 | # Contact me: 33 | Join my Discord: https://discordapp.com/invite/YhBUUSr 34 | Bohemia Interactive Forum Thread: https://forums.bohemia.net/forums/topic/223835-api-bec-rcon-api-for-python-and-discord/ 35 | 36 | # Discord: 37 | 38 | A Discord module using this API can be found here: 39 | https://github.com/Yoshi-E/jmwBOT/tree/master/modules/rcon 40 | 41 | # Documentation 42 | ## Event Handlers: 43 | The passed functions can by async and can be class objects. 44 | 45 | | Event | passed args | 46 | |:----------------------- |:--------------| 47 | | on_disconnect | none | 48 | | login_Sucess | none | 49 | | login_fail | none | 50 | | on_command_fail | none | 51 | | received_ServerMessage | message: str | 52 | | received_CommandMessage | message: str | 53 | 54 | ## Variables: 55 | * rcon_client.serverMessage: Contains all recent messages (limit = 100) Format: [datetime: datetime, message: str] 56 | * rcon_client.serverCommandData: Contains all returned data from commands (limit = 10) Format: [datetime: datetime, data: str] 57 | * rcon_client.disconnected: When connected = False, else True 58 | * rcon_client.serverPort: ServerPort (int) 59 | * rcon_client.serverIP: ServerIP (str) 60 | * rcon_client.rconPassword: ServerPassword (str) 61 | * rcon_client.Events: List of all user added Event handlers Format: [str(event_name), function(custom_function)] 62 | 63 | ## API Functions: 64 | 65 | ###### ARC = ARC(serverIP: str, RConPassword: str, serverPort = 2302, options = {}) 66 | * serverIP: IPv4 adress in the format: 000.000.000.000 - 255.255.255.255 67 | * RConPassword: str your Rcon password 68 | * serverPort: int port Rcon is running on your server 69 | options is an diconatry for addional settings: 70 | * timeoutSec: int time in seconds a RCon command has to be executed within (Default: 5, Min: 0.2, Max: None) 71 | * autosaveBans: boolean Saves bans to file when ever a ban is added or removed (Default: False) 72 | * debug: boolean Prints additonal package and debug information into console (Default: False) 73 | This class constructor automatically connects to given server and attempts to maintain the connection. 74 | ###### ARC.disconnect() 75 | Closed the connection to the server and fires the Event "on_disconnect". 76 | ###### ARC.connect() 77 | Connects to the server. 78 | ###### ARC.reconnect() 79 | Closes the connection and connects to the server. 80 | ###### ARC.authorize() 81 | Authorizes the connection using the RConPassword 82 | ###### ARC.send(command: str) 83 | Waits for an opportunity to send a command to the rcon server. 84 | Only one send will be executed at a time. At most ARC.max_waiting_for_send (Defaut: 10) can be waiting. 85 | Will raise the "Failed to send command!" exception if it failed to send the command within the timeout limit. 86 | ARC.activeSend tracks how many commands are trying to be send at the same time. 87 | ###### ARC.add_Event(event_name: str, function: function) 88 | Events are: "on_command_fail", "on_disconnect", "login_Sucess", "login_fail", "received_ServerMessage" and "received_CommandMessage". 89 | Function can be class function and can be asynchronous. 90 | Addtional, custom parameters however can not be passed. 91 | 92 | ## RCon Commands: 93 | See rcon.py for details 94 | * command 95 | * kickPlayer 96 | * sayGlobal 97 | * sayPlayer 98 | * loadScripts 99 | * maxPing 100 | * changePassword 101 | * loadBans 102 | * getPlayers 103 | * getPlayersArray 104 | * getAdmins 105 | * getAdminsArray 106 | * getMissions 107 | * loadMission 108 | * banPlayer 109 | * addBan 110 | * removeBan 111 | * getBansArray 112 | * getBans 113 | * writeBans 114 | * getBEServerVersion 115 | 116 | ## Arma 3 Commands 117 | See https://community.bistudio.com/wiki/Multiplayer_Server_Commands for details 118 | * lock 119 | * unlock 120 | * shutdown 121 | * restart 122 | * restartServer 123 | * restartserveraftermission 124 | * shutdownserveraftermission 125 | * reassign 126 | * monitords 127 | * goVote 128 | 129 | 130 | ## Donate 131 | 132 | [![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://paypal.me/YoshiEU) 133 | 134 | 135 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | name = "bec_rcon" -------------------------------------------------------------------------------- /bec_rcon.py: -------------------------------------------------------------------------------- 1 | #Author: Yoshi_E 2 | #Date: 2019.06.14 3 | #https://www.battleye.com/downloads/BERConProtocol.txt 4 | 5 | #Supported Events: 6 | # "on_disconnect" passed_args = None 7 | # "login_Sucess" passed_args = None 8 | # "login_fail" passed_args = None 9 | # "received_ServerMessage" passed_args = message: str 10 | # "received_CommandMessage" passed_args = message: str 11 | # "on_command_fail" passed_args = None 12 | 13 | 14 | 15 | import socket 16 | import re 17 | import zlib 18 | import asyncio 19 | from collections import deque 20 | import datetime 21 | import codecs 22 | import inspect 23 | import logging 24 | # Author: Yoshi_E 25 | # Date: 2019.06.14 26 | # Updated: 2023.04.20 27 | # Found on github: https://github.com/Yoshi-E/Python-BEC-RCon 28 | # Python3.6 Implementation of data protocol: https://www.battleye.com/downloads/BERConProtocol.txt 29 | # License: https://creativecommons.org/licenses/by-nc-sa/4.0/ 30 | 31 | 32 | 33 | class RCON(): 34 | SERVERDATA_AUTH = 3 35 | SERVERDATA_EXECCOMMAND = 2 36 | SERVERDATA_RESPONSE_VALUE = 0 37 | 38 | def __init__(self, serverIP: str, RConPassword: str, serverPort = 2302, logger = None, options = {}): 39 | 40 | self.options = { 41 | 'timeoutSec' : 10, 42 | 'autosaveBans' : False, 43 | } 44 | 45 | self.logger = logger 46 | if not logger: 47 | self.logger = logging.getLogger(__name__) 48 | 49 | # Text encoding (not all codings are supported) 50 | self.codec = "iso-8859-1" 51 | 52 | # Connection status 53 | self.disconnected = True 54 | 55 | # Stores all recent server messages (Format: array([datetime, msg],...)) 56 | self.serverMessage = deque(maxlen=100) 57 | 58 | # Event Handlers (Format: array([name, function], [name2, function2]...) 59 | self.eventHandlers = [] 60 | 61 | # Multi-packet buffer 62 | self.multiPackets = [] 63 | 64 | # Timestamps of last send and receive 65 | self.lastSend = datetime.datetime.now() 66 | self.lastReceived = datetime.datetime.now() 67 | self.lastAuth = datetime.datetime(1900, 1, 1, 0, 0, 0) 68 | 69 | # Locks sending until space to send is available 70 | self.sendLock = False 71 | 72 | # Number of commands waiting to be sent (limited to 10) 73 | # Prevents overflow from too many queued commands 74 | self.numPendingCommands = 0 75 | 76 | # Limits how many data packages can be sent at the same time 77 | self.maxPendingCommands = 10 78 | 79 | # Stores all recent command returned data (Format: array([datetime, msg],...)) 80 | self.serverCommandData = deque(maxlen=1000) 81 | 82 | # Denotes if the object is being destroyed 83 | self.terminated = False 84 | 85 | if (type(serverPort) != int or type(RConPassword) != str or type(serverIP) != str): 86 | raise Exception('Wrong constructor parameter type(s)!') 87 | if(serverIP == "localhost"): #localhost is not supported 88 | self.serverIP = "127.0.0.1" 89 | else: 90 | self.serverIP = serverIP 91 | self.serverPort = serverPort 92 | self.rconPassword = RConPassword 93 | self.options = {**self.options, **options} 94 | self.connect() 95 | 96 | def __del__(self): 97 | self.terminated = True 98 | self.disconnect() 99 | 100 | def disconnect(self): 101 | if (self.disconnected): 102 | return None 103 | self.logger.info("[rcon] Disconnected") 104 | self.socket.close() 105 | self.socket = None 106 | self.disconnected = True 107 | self.on_disconnect() 108 | 109 | def connect(self): 110 | self.sendLock = False 111 | if (self.disconnected == False): 112 | self.disconnect() 113 | self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 114 | self.socket.connect((self.serverIP, self.serverPort)) # #"udp://"+ 115 | if (self.socket == False): 116 | raise socket.error('Failed to create socket!') 117 | 118 | self.socket.setblocking(0) 119 | self.authorize() 120 | self.disconnected = False 121 | 122 | #spawn async tasks 123 | self.listenForDataTask = asyncio.ensure_future(self.listenForData()) 124 | self.keepAliveLoopTask = asyncio.ensure_future(self.keepAliveLoop()) 125 | self.checkLoginOkTask = asyncio.ensure_future(self.checkLoginOk()) 126 | 127 | def reconnect(self): 128 | self.disconnect() 129 | self.connect() 130 | return None 131 | 132 | # Sends the login data to the server in order to send commands later 133 | def authorize(self): 134 | self.sendLock = True # released by checkLoginOk() 135 | sent = self.writeToSocket(self.getLoginMessage()) 136 | 137 | # sends the RCon command, but waits until command is confirmed before sending another one 138 | async def send(self, command: str): 139 | self.numPendingCommands += 1 140 | for _ in range(0,10 * self.options['timeoutSec']): 141 | if(self.numPendingCommands > self.maxPendingCommands): 142 | break 143 | if(self.sendLock == False): #Lock released by waitForResponse() 144 | self.sendLock = True 145 | if (self.disconnected): 146 | raise ConnectionError('Failed to send command, because the connection is closed!') 147 | head = self.getHead(command) 148 | if (self.writeToSocket(head, command) == False): 149 | raise ConnectionError('Failed to send command!') 150 | self.numPendingCommands -= 1 151 | 152 | return True 153 | else: 154 | await asyncio.sleep(0.1) #watis 0.1 second before checking again 155 | self.numPendingCommands -= 1 156 | if(self.numPendingCommands > self.maxPendingCommands): 157 | raise TimeoutError("Failed to send in time: "+command+ " too many commands in queue >"+str(self.maxPendingCommands)) 158 | else: 159 | self.sendLock = False 160 | raise TimeoutError("Failed to send in time: "+command) 161 | 162 | # Writes the given message to the socket 163 | def writeToSocket(self, head, command=""): 164 | self.lastSend = datetime.datetime.now() 165 | a = bytes(head.encode(self.codec, 'replace')) 166 | b = bytes.fromhex(command.encode("utf-8", 'replace').hex()) 167 | return self.socket.send(a+b) 168 | 169 | # Generates the password's CRC32 data 170 | def getAuthCRC(self): 171 | data = b'\xff\x00' + (self.rconPassword.strip()).encode(self.codec) 172 | authCRC = '%x' % zlib.crc32(bytes(data)) 173 | authCRC = [authCRC[-2:], authCRC[-4:-2], authCRC[-6:-4], authCRC[0:2]] 174 | return authCRC 175 | 176 | # Generates the message's CRC32 data 177 | def getMsgCRC(self, command): 178 | header = b'\xff\x01\x00' 179 | payload = bytes.fromhex(command.encode(self.codec, 'replace').hex()) 180 | data = header+payload 181 | msgCRC = ('%x' % zlib.crc32(data)).zfill(8) 182 | msgCRC = [msgCRC[-2:], msgCRC[-4:-2], msgCRC[-6:-4], msgCRC[0:2]] 183 | return msgCRC 184 | 185 | def getHead(self, command): 186 | msgCRC = self.getMsgCRC(command) 187 | ascii_chars = [chr(int(hex_str, 16)) for hex_str in msgCRC] 188 | return 'BE' + ''.join(ascii_chars) + '\xff\x01\x00' 189 | 190 | def getLoginMessage(self): 191 | authCRC = self.getAuthCRC() 192 | ascii_chars = [chr(int(hex_str, 16)) for hex_str in authCRC] 193 | loginMsg = 'BE' + ''.join(ascii_chars) + '\xff\x00' + self.rconPassword 194 | self.logger.debug("loginMsg", loginMsg) 195 | return loginMsg 196 | 197 | 198 | ################################################################################################### 199 | ##### common functions #### 200 | ################################################################################################### 201 | # Debug funcion to view special chars 202 | def String2Hex(self,string): 203 | return string.encode(self.codec, 'replace').hex() 204 | 205 | #returns when a new command package was receive 206 | async def waitForResponse(self): 207 | d = len(self.serverCommandData) 208 | timeout = self.options['timeoutSec'] * 20 #10 = one second 209 | for i in range(0,timeout): 210 | if(d < len(self.serverCommandData)): #new command package was received 211 | self.sendLock = False #release the lock 212 | data = self.serverCommandData.pop()[1] 213 | if(len(self.serverCommandData) >= self.serverCommandData.maxlen/2): 214 | self.serverCommandData.clear() 215 | return data 216 | await asyncio.sleep(0.05) 217 | self.logger.info("[rcon] Failed to keep connection - Disconnected") 218 | self.on_command_fail("Connection timed out") 219 | self.sendLock = False 220 | self.disconnect() #Connection Lost 221 | raise TimeoutError("Command timed out") 222 | 223 | 224 | def sendReciveConfirmation(self, sequence): 225 | if (self.disconnected): 226 | raise ConnectionError('Failed to send command, because the connection is closed!') 227 | 228 | #calculate CRC32 229 | data = b'\xff\x02' + sequence.encode(self.codec) 230 | msgCRC = ('%x' % zlib.crc32(data)).zfill(8) 231 | msgCRC = [msgCRC[-2:], msgCRC[-4:-2], msgCRC[-6:-4], msgCRC[0:2]] 232 | 233 | #generate send message 234 | ascii_chars = [chr(int(hex_str, 16)) for hex_str in msgCRC] 235 | msg = 'BE' + ''.join(ascii_chars) + '\xff\x02' + sequence 236 | 237 | if (self.writeToSocket(msg) == False): 238 | raise Exception('Failed to send confirmation!') 239 | 240 | async def listenForData(self): 241 | while (self.disconnected == False): 242 | answer = None 243 | try: 244 | answer = self.socket.recv(4096).decode(self.codec) 245 | header = answer[:7] 246 | crc32_checksum = header[2:-1] # TODO: verify checksum 247 | 248 | body = ""+self.String2Hex(answer[9:]) 249 | body = codecs.decode(body, "hex", errors="strict") # 250 | body = body.decode(encoding="utf-8", errors='replace') #some encoding magic (iso-8859-1(with utf-8 chars) --> utf-8) 251 | 252 | packet_type = self.String2Hex(answer[7]) 253 | 254 | self.lastReceived = datetime.datetime.now() 255 | self.logger.debug("[rcon] Received Package type: {}".format(packet_type)) 256 | self.logger.debug("[rcon] Data: {}".format(body)) 257 | if(packet_type=="02"): 258 | self.received_ServerMessage(answer, body) 259 | if(packet_type=="01"): 260 | self.received_CommandMessage(answer, body) 261 | if(packet_type=="00"): #"Login packet" 262 | if (ord(answer[len(answer)-1]) == 0): #Raise error when login failed 263 | excption = 'Login failed, wrong password or wrong port!' 264 | self.login_fail(excption) 265 | raise PermissionError(excption) 266 | else: 267 | self.login_Sucess() 268 | except BlockingIOError as e: 269 | pass 270 | except Exception as e: 271 | self.logger.exception(f"listenForData: {e}") 272 | 273 | if not answer: 274 | await asyncio.sleep(0.2) 275 | 276 | async def keepAliveLoop(self): 277 | while (self.disconnected == False): 278 | #package needs to be send every min:1s, max:44s 279 | diff = datetime.datetime.now() - self.lastReceived 280 | if(diff.total_seconds() >= 40): 281 | await self.keepAlive() 282 | await asyncio.sleep(2) 283 | 284 | #Keep the stream alive. Send package to BE server. Use function before 45 seconds. 285 | async def keepAlive(self): 286 | try: 287 | self.logger.debug('[rcon] --Keep connection alive--'+"\n") 288 | await self.getBEServerVersion() 289 | except Exception as e: 290 | self.logger.debug("[rcon] Failed to keep Alive - Disconnected") 291 | self.disconnect() #connection lost 292 | 293 | # Check if the login was sucessfull 294 | async def checkLoginOk(self): 295 | # Verify login succeeded by waiting for server response: 296 | for _ in range(0, self.options['timeoutSec']*10): 297 | await asyncio.sleep(0.1) 298 | 299 | delta = datetime.datetime.now() - self.lastAuth 300 | if(delta.total_seconds() <= self.options['timeoutSec']): 301 | self.sendLock = False 302 | self.logger.debug('[rcon] --Login ok--'+"\n") 303 | return True 304 | 305 | self.sendLock = False 306 | self.login_fail("Login: Connection timed out") 307 | self.disconnect() 308 | raise TimeoutError("Login: Connection timed out") 309 | 310 | 311 | ################################################################################################### 312 | ##### event handler #### 313 | ################################################################################################### 314 | def add_Event(self, name: str, func): 315 | events = ["on_command_fail", "on_disconnect", "login_Sucess", "login_fail", "received_ServerMessage", "received_CommandMessage"] 316 | if(name in events): 317 | self.eventHandlers.append([name,func]) 318 | else: 319 | raise ValueError("Failed to add unkown event: "+name) 320 | 321 | 322 | def check_Event(self, parent, *args): 323 | if(self.terminated == True): 324 | return 325 | for event in self.eventHandlers: 326 | func = event[1] 327 | if(inspect.iscoroutinefunction(func)): #is async 328 | if(event[0]==parent): 329 | if(len(args)>0): 330 | asyncio.ensure_future(func(args)) 331 | else: 332 | asyncio.ensure_future(func()) 333 | else: 334 | if(event[0]==parent): 335 | if(len(args)>0): 336 | func(args) 337 | else: 338 | func() 339 | 340 | ################################################################################################### 341 | ##### event functions #### 342 | ################################################################################################### 343 | 344 | def on_disconnect(self): 345 | self.check_Event("on_disconnect") 346 | 347 | def login_Sucess(self): 348 | self.lastAuth = datetime.datetime.now() 349 | self.check_Event("login_Sucess") 350 | 351 | def login_fail(self, exception): 352 | self.disconnect() 353 | self.check_Event("login_fail", exception) 354 | 355 | def received_ServerMessage(self, packet, message): 356 | self.serverMessage.append([datetime.datetime.now(), message]) 357 | self.sendReciveConfirmation(packet[8]) #confirm with sequence id from packet 358 | self.check_Event("received_ServerMessage", message) 359 | 360 | #waitForResponse() handles all inbound packets, you can still fetch them here though. 361 | def received_CommandMessage(self, packet, message): 362 | if(len(message)>3 and self.String2Hex(message[0]) =="00"): #is multi packet 363 | self.multiPackets.append(message[3:]) 364 | if(int(self.String2Hex(message[1]),16)-1 == int(self.String2Hex(message[2]),16)): 365 | self.serverCommandData.append([datetime.datetime.now(), "".join(self.multiPackets)]) 366 | self.multiPackets = [] 367 | else: #Normal Package 368 | self.serverCommandData.append([datetime.datetime.now(), message]) 369 | self.check_Event("received_CommandMessage", message) 370 | 371 | def on_command_fail(self, exception): 372 | self.check_Event("on_command_fail", exception) 373 | 374 | 375 | 376 | ################################################################################################### 377 | ##### BEC Commands #### 378 | ################################################################################################### 379 | # 380 | # *** Warning *** 381 | # Depending on your configuation of BEC not all commands might work 382 | # *** Warning *** 383 | 384 | class RCON_ARMA(RCON): 385 | # Converts BE text "array" list to array 386 | def formatList(self, str): 387 | #Create return array 388 | result = [] 389 | #Loop True the main arrays, each holding a value 390 | for pair in str: 391 | #Combines each main value into new array 392 | result.append([]) 393 | for val in pair: 394 | result[-1].append(val.strip()) 395 | return result 396 | 397 | # Remove control characte rs 398 | def cleanList(self, str): 399 | return re.sub('/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F]/', '', str) 400 | 401 | # Sends a custom command to the server 402 | async def command(self, command: str): 403 | await self.send(command) 404 | return await self.waitForResponse() 405 | 406 | # Kicks a player who is currently on the server 407 | async def kickPlayer(self, player, reason = 'Admin Kick'): 408 | if (type(player) != int and type(player) != str): 409 | raise Exception('Expected parameter 1 to be string or integer, got %s' % type(player)) 410 | if (type(reason) != str): 411 | raise Exception('Expected parameter 2 to be string, got %s' % type(reason)) 412 | await self.send("kick "+str(player)+" "+reason) 413 | return await self.waitForResponse() 414 | 415 | # Sends a global message to all players 416 | async def sayGlobal(self, message: str): 417 | await self.send("Say -1 "+message) 418 | return await self.waitForResponse() 419 | 420 | # Sends a message to a specific player 421 | async def sayPlayer(self, player: int, message: str): 422 | await self.send("Say "+str(player)+" "+message) 423 | return await self.waitForResponse() 424 | 425 | # Loads the "scripts.txt" file without the need to restart the server 426 | async def loadScripts(self): 427 | await self.send('loadScripts') 428 | return await self.waitForResponse() 429 | 430 | # Changes the MaxPing value. If a player has a higher ping, he will be kicked from the server 431 | async def maxPing(self, ping: int): 432 | await self.send("MaxPing "+str(ping)) 433 | return await self.waitForResponse() 434 | 435 | # Changes the RCon password 436 | async def changePassword(self, password: str): 437 | await self.send(f"RConPassword {password}") 438 | return await self.waitForResponse() 439 | 440 | # (Re)load the BE ban list from bans.txt 441 | async def loadBans(self): 442 | await self.send('loadBans') 443 | return await self.waitForResponse() 444 | 445 | # Gets a list of all players currently on the server 446 | async def getPlayers(self): 447 | await self.send('players') 448 | return await self.waitForResponse() 449 | 450 | # Gets a list of all players currently on the server as an array 451 | async def getPlayersArray(self): 452 | playersRaw = await self.getPlayers() 453 | players = self.cleanList(playersRaw) 454 | data = re.findall(r"(\d+)\s+(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+\b)\s+(\d+)\s+([0-9a-fA-F]+)\(\w+\)\s([\S ]+)", players) 455 | return self.formatList(data) 456 | 457 | # Gets a list of all admins connected to the server 458 | async def getAdmins(self): 459 | await self.send('admins') 460 | result = await self.waitForResponse() 461 | return result #strip timedate 462 | 463 | # Gets a list of all players currently on the server as an array 464 | async def getAdminsArray(self): 465 | adminsRaw = await self.getAdmins() 466 | admins = self.cleanList(adminsRaw) 467 | str = re.findall(r"(\d+)\s+(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+\b)", admins) 468 | return self.formatList(str) 469 | 470 | # Gets a list of all bans 471 | async def getMissions(self): 472 | await self.send('missions') 473 | return await self.waitForResponse() 474 | 475 | # Loads a mission 476 | # Mission file name without .pbo at the end! 477 | async def loadMission(self, mission: str): 478 | await self.send('#mission '+mission) 479 | return await self.waitForResponse() 480 | 481 | # Loads Events 482 | async def loadEvents(self): 483 | await self.send('loadEvents') 484 | return await self.waitForResponse() 485 | 486 | # Ban a player's BE GUID from the server. If time is not specified or 0, the ban will be permanent. 487 | # If reason is not specified the player will be kicked with the message "Banned". 488 | async def banPlayer(self, player_id, reason = 'Banned', time = 0): 489 | if (type(player_id) != str and type(player_id) != int): 490 | raise Exception('Expected parameter 1 to be integer or string, got %s' % type(player_id)) 491 | if (type(reason) != str or type(time) != int): 492 | raise Exception('Wrong parameter type(s)!') 493 | await self.send("ban "+str(player_id)+" "+str(time)+" "+reason) 494 | if (self.options['autosaveBans']): 495 | self.writeBans() 496 | return await self.waitForResponse() 497 | 498 | # Same as "banPlayer", but allows to ban a player that is not currently on the server 499 | async def addBan(self, guid: int, reason = 'Banned', time = 0): 500 | await self.send("addBan "+guid+" "+str(time)+" "+reason) 501 | if (self.options['autosaveBans']): 502 | self.writeBans() 503 | return await self.waitForResponse() 504 | 505 | # Removes a ban 506 | async def removeBan(self, banId: int): 507 | await self.send("removeBan "+str(banId)) 508 | if (self.options['autosaveBans']): 509 | self.writeBans() 510 | return await self.waitForResponse() 511 | 512 | # Gets an array of all bans 513 | async def getBansArray(self): 514 | bansRaw = await self.getBans() 515 | bans = self.cleanList(bansRaw) 516 | str = re.findall(r'(\d+)\s+([0-9a-fA-F]+)\s([perm|\d]+)\s([\S ]+)', bans) 517 | return self.formatList(str) 518 | 519 | # Gets a list of all bans 520 | async def getBans(self): 521 | await self.send('bans') 522 | return await self.waitForResponse() 523 | 524 | # Removes expired bans from bans file 525 | async def writeBans(self): 526 | await self.send('writeBans') 527 | return await self.waitForResponse() 528 | 529 | # Gets the current version of the BE server 530 | async def getBEServerVersion(self): 531 | await self.send('version') 532 | return await self.waitForResponse() 533 | 534 | ################################################################################################### 535 | ##### Arma Server Commands #### 536 | ################################################################################################### 537 | # Commands starting with a '#' can be execuded, but will return no data 538 | 539 | # Locks the server. No one will be able to join 540 | async def lock(self): 541 | await self.send('#lock') 542 | return await self.waitForResponse() 543 | 544 | # Unlocks the Server 545 | async def unlock(self): 546 | await self.send('#unlock') 547 | return await self.waitForResponse() 548 | 549 | # Shutdowns the Server 550 | # args: [x, "abort", "info"] x= time in seconds till shutdown 551 | async def shutdown(self): 552 | await self.send('#shutdown') 553 | return await self.waitForResponse() 554 | 555 | # Restart mission with current player slot selection 556 | async def restart(self): 557 | await self.send('#restart') 558 | return await self.waitForResponse() 559 | 560 | # Shuts down and restarts the server immediately 561 | async def restartServer(self): 562 | await self.send('#restartserver') 563 | return await self.waitForResponse() 564 | 565 | # Shuts down and restarts the server after mission ends 566 | async def restartserveraftermission(self): 567 | await self.send('#restartserveraftermission') 568 | return await self.waitForResponse() 569 | 570 | # Shuts down the server after mission ends 571 | async def shutdownserveraftermission(self): 572 | await self.send('#shutdownserveraftermission') 573 | return await self.waitForResponse() 574 | 575 | # Restart the mission with new player slot selection 576 | async def reassign(self): 577 | await self.send('#reassign') 578 | return await self.waitForResponse() 579 | 580 | # Shows performance information in the dedicated server console. Interval 0 means to stop monitoring. 581 | async def monitords(self, inveral: int): 582 | await self.send('#monitords '+str(inveral)) 583 | return await self.waitForResponse() 584 | 585 | # Users can vote for the mission selection. 586 | async def goVote(self): 587 | await self.send('#vote missions') 588 | return await self.waitForResponse() -------------------------------------------------------------------------------- /example/api_example.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | 3 | import sys, os 4 | parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) 5 | sys.path.insert(0, parent_dir) 6 | from bec_rcon import RCON_ARMA 7 | 8 | ################################################################################################### 9 | ##### Custom Functions called by the Event Handler #### 10 | ################################################################################################### 11 | 12 | def msg(args): 13 | message = args[0] 14 | print(message) #Prints received message 15 | 16 | def disco(): 17 | print("Disconnected") 18 | 19 | def fail(exception): 20 | print(f"login fail: {exception}") 21 | 22 | def sucess(): 23 | print("login sucess") 24 | #Now you can for example call to reconnect the client (add a delay) 25 | #sleep(60) 26 | #arma_rcon.connect() 27 | 28 | ################################################################################################### 29 | ##### Async task keeping the script alive, while a connection exsits #### 30 | ################################################################################################### 31 | 32 | # The execution of rcon commands is asynchronous and requires an "await" in an "async" function 33 | # All commands are listed in BEC commands in rcon.py 34 | async def main(): 35 | print("Players:",await arma_rcon.getPlayersArray()) #get Array with all player on server 36 | await arma_rcon.listenForDataTask # waits until on_disconnect 37 | print("Connection Lost") 38 | # arma_rcon.serverMessage # Contains all recent messages (limit = 100) Format: [obj(datetime), Str(Message)] 39 | # arma_rcon.serverCommandData # Contains all recent command returned data (limit = 10) Format: [obj(datetime), Str(Data)] 40 | # arma_rcon.disconnect() # Disconnects the client 41 | # arma_rcon.connect() # Logs back in 42 | 43 | ################################################################################################### 44 | ##### Main Program #### 45 | ################################################################################################### 46 | 47 | if __name__ == "__main__": 48 | ip = "000.000.000.000" #Your Server IP 49 | pw = "PASSWORD" #Your Rcon Password 50 | port = 3302 #Rcon Port 51 | 52 | 53 | # creating the instance will also automatically create an async method "keepAliveLoop" 54 | # that will maintain the connection 55 | arma_rcon = RCON_ARMA(ip, pw, port) 56 | 57 | # Simply attach the events to the client that you need 58 | arma_rcon.add_Event("received_ServerMessage", msg) 59 | arma_rcon.add_Event("on_disconnect", disco) 60 | arma_rcon.add_Event("login_fail", fail) 61 | arma_rcon.add_Event("login_Sucess", sucess) 62 | 63 | loop = asyncio.get_event_loop() 64 | loop.run_until_complete(main()) 65 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | socket 2 | re 3 | zlib 4 | asyncio 5 | traceback 6 | collections 7 | datetime 8 | codecs 9 | inspect -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # Learn more: https://github.com/Yoshi-E/Python-BEC-RCon 2 | # python setup.py sdist bdist_wheel 3 | # pip install dist/bec_rcon-0.1.0-py3-none-any.whl 4 | from setuptools import setup, find_packages 5 | 6 | with open('README.md') as f: 7 | readme = f.read() 8 | 9 | with open('LICENSE') as f: 10 | license = f.read() 11 | 12 | setup( 13 | name='bec_rcon', 14 | version='0.2.0', 15 | description='API for Battleye extended controls - Arma3', 16 | long_description=readme, 17 | author='Yoshi_E', 18 | author_email='notifyYoshi@yahoo.de', 19 | url='https://github.com/Yoshi-E/Python-BEC-RCon', 20 | license=license, 21 | classifiers=[ 22 | # How mature is this project? Common values are 23 | # 3 - Alpha 24 | # 4 - Beta 25 | # 5 - Production/Stable 26 | 'Development Status :: 4 - Alpha', 27 | 28 | # Indicate who your project is intended for 29 | 'Intended Audience :: Developers', 30 | 'Topic :: Software Development :: Tools', 31 | 32 | # Pick your license as you wish (should match "license" above) 33 | 'License :: Attribution-NonCommercial-ShareAlike', 34 | 35 | # Specify the Python versions you support here. 36 | 'Programming Language :: Python :: 3.11' 37 | ], 38 | keywords='arma rcon battleye bec administration', 39 | project_urls={ 40 | 'Say Thanks!': 'https://forums.bohemia.net/forums/topic/223835-api-bec-rcon-api-for-python-and-discord/', 41 | 'Source': 'https://github.com/Yoshi-E/Python-BEC-RCon', 42 | 'Tracker': 'https://github.com/Yoshi-E/Python-BEC-RCon/issues', 43 | }, 44 | py_modules=["bec_rcon"], 45 | python_requires='>=3.11', 46 | packages=find_packages(exclude=('example')) 47 | ) --------------------------------------------------------------------------------