├── .gitignore ├── .pre-commit-config.yaml ├── LICENSE ├── README.md ├── examples ├── events │ ├── README.md │ └── __main__.py ├── hotkeys │ ├── README.md │ ├── __main__.py │ └── setup.py ├── levels │ ├── README.md │ └── __main__.py └── scene_rotate │ ├── README.md │ └── __main__.py ├── obsws_python ├── __init__.py ├── baseclient.py ├── callback.py ├── error.py ├── events.py ├── reqs.py ├── subs.py ├── util.py └── version.py ├── pyproject.toml ├── setup.py └── tests ├── __init__.py ├── test_attrs.py ├── test_callback.py ├── test_error.py └── test_request.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # Distribution / packaging 7 | .Python 8 | build/ 9 | develop-eggs/ 10 | dist/ 11 | downloads/ 12 | eggs/ 13 | .eggs/ 14 | lib/ 15 | lib64/ 16 | parts/ 17 | sdist/ 18 | var/ 19 | wheels/ 20 | *.egg-info/ 21 | .installed.cfg 22 | *.egg 23 | MANIFEST 24 | 25 | # Unit test / coverage reports 26 | htmlcov/ 27 | .tox/ 28 | .nox/ 29 | .coverage 30 | .coverage.* 31 | .cache 32 | nosetests.xml 33 | coverage.xml 34 | *.cover 35 | .hypothesis/ 36 | .pytest_cache/ 37 | 38 | # Environments 39 | .env 40 | .venv 41 | env/ 42 | venv/ 43 | ENV/ 44 | env.bak/ 45 | venv.bak/ 46 | .hatch 47 | 48 | # pyenv 49 | # For a library or package, you might want to ignore these files since the code is 50 | # intended to run in multiple environments; otherwise, check them in: 51 | .python-version 52 | 53 | # Test/config 54 | test-*.py 55 | config.toml 56 | obsws.log 57 | 58 | .vscode/ -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: local 3 | hooks: 4 | - id: format 5 | name: format 6 | entry: hatch run style:fmt 7 | language: system 8 | pass_filenames: false 9 | verbose: true 10 | files: \.(py)$ 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![PyPI version](https://badge.fury.io/py/obsws-python.svg)](https://badge.fury.io/py/obsws-python) 2 | [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://github.com/aatikturk/obsstudio_sdk/blob/main/LICENSE) 3 | [![Hatch project](https://img.shields.io/badge/%F0%9F%A5%9A-Hatch-4051b5.svg)](https://github.com/pypa/hatch) 4 | [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) 5 | [![Imports: isort](https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336)](https://pycqa.github.io/isort/) 6 | 7 | # A Python SDK for OBS Studio WebSocket v5.0 8 | 9 | Not all endpoints in the official documentation are implemented. 10 | 11 | ## Requirements 12 | 13 | - [OBS Studio](https://obsproject.com/) 14 | - [OBS Websocket v5 Plugin](https://github.com/obsproject/obs-websocket/releases/tag/5.0.0) 15 | - With the release of OBS Studio version 28, Websocket plugin is included by default. But it should be manually installed for earlier versions of OBS. 16 | - Python 3.9 or greater 17 | 18 | ### How to install using pip 19 | 20 | ``` 21 | pip install obsws-python 22 | ``` 23 | 24 | ### How to Use 25 | 26 | By default the clients connect with parameters: 27 | 28 | - `host`: "localhost" 29 | - `port`: 4455 30 | - `password`: "" 31 | - `timeout`: None 32 | 33 | You may override these parameters by storing them in a toml config file or passing them as keyword arguments. 34 | 35 | Order of precedence: keyword arguments then config file then default values. 36 | 37 | #### `config file` 38 | 39 | A valid `config.toml` might look like this: 40 | 41 | ```toml 42 | [connection] 43 | host = "localhost" 44 | port = 4455 45 | password = "mystrongpass" 46 | ``` 47 | 48 | It should be placed in your user home directory. 49 | 50 | #### Otherwise: 51 | 52 | Example `__main__.py`: 53 | 54 | ```python 55 | import obsws_python as obs 56 | 57 | # pass conn info if not in config.toml 58 | cl = obs.ReqClient(host='localhost', port=4455, password='mystrongpass', timeout=3) 59 | 60 | # Toggle the mute state of your Mic input 61 | cl.toggle_input_mute('Mic/Aux') 62 | ``` 63 | 64 | ### Requests 65 | 66 | Method names for requests match the API calls but snake cased. If a successful call is made with the Request client and the response is expected to contain fields then a response object will be returned. You may then access the response fields as class attributes. They will be snake cased. 67 | 68 | example: 69 | 70 | ```python 71 | # load conn info from config.toml 72 | cl = obs.ReqClient() 73 | 74 | # GetVersion, returns a response object 75 | resp = cl.get_version() 76 | # Access it's field as an attribute 77 | print(f"OBS Version: {resp.obs_version}") 78 | 79 | 80 | # SetCurrentProgramScene 81 | cl.set_current_program_scene("BRB") 82 | ``` 83 | 84 | #### `send(param, data=None, raw=False)` 85 | 86 | If you prefer to work with the JSON data directly the {ReqClient}.send() method accepts an argument, `raw`. If set to True the raw response data will be returned, instead of a response object. 87 | 88 | example: 89 | 90 | ```python 91 | resp = cl_req.send("GetVersion", raw=True) 92 | 93 | print(f"response data: {resp}") 94 | ``` 95 | 96 | For a full list of requests refer to [Requests][obsws-reqs] 97 | 98 | ### Events 99 | 100 | When registering a callback function use the name of the expected API event in snake case form, prepended with "on\_". 101 | 102 | example: 103 | 104 | ```python 105 | # load conn info from config.toml 106 | cl = obs.EventClient() 107 | 108 | def on_scene_created(data): 109 | ... 110 | 111 | # SceneCreated 112 | cl.callback.register(on_scene_created) 113 | 114 | def on_input_mute_state_changed(data): 115 | ... 116 | 117 | # InputMuteStateChanged 118 | cl.callback.register(on_input_mute_state_changed) 119 | 120 | # returns a list of currently registered events 121 | print(cl.callback.get()) 122 | 123 | # You may also deregister a callback 124 | cl.callback.deregister(on_input_mute_state_changed) 125 | ``` 126 | 127 | `register(fns)` and `deregister(fns)` accept both single functions and lists of functions. 128 | 129 | For a full list of events refer to [Events][obsws-events] 130 | 131 | ### Attributes 132 | 133 | For both request responses and event data you may inspect the available attributes using `attrs()`. 134 | 135 | example: 136 | 137 | ```python 138 | resp = cl.get_version() 139 | print(resp.attrs()) 140 | 141 | def on_scene_created(data): 142 | print(data.attrs()) 143 | ``` 144 | 145 | ### Errors 146 | 147 | - `OBSSDKError`: Base error class. 148 | - `OBSSDKTimeoutError`: Raised if a timeout occurs during sending/receiving a request or receiving an event 149 | - `OBSSDKRequestError`: Raised when a request returns an error code. 150 | - The following attributes are available: 151 | - `req_name`: name of the request. 152 | - `code`: request status code. 153 | - For a full list of status codes refer to [Codes][obsws-codes] 154 | 155 | ### Logging 156 | 157 | If you want to see the raw messages simply set log level to DEBUG 158 | 159 | example: 160 | 161 | ```python 162 | import obsws_python as obs 163 | import logging 164 | 165 | 166 | logging.basicConfig(level=logging.DEBUG) 167 | ... 168 | ``` 169 | 170 | ### Tests 171 | 172 | Install [hatch][hatch-install] and then: 173 | 174 | ``` 175 | hatch test 176 | ``` 177 | 178 | ### Official Documentation 179 | 180 | For the full documentation: 181 | 182 | - [OBS Websocket SDK][obsws-pro] 183 | 184 | 185 | [obsws-reqs]: https://github.com/obsproject/obs-websocket/blob/master/docs/generated/protocol.md#requests 186 | [obsws-events]: https://github.com/obsproject/obs-websocket/blob/master/docs/generated/protocol.md#events 187 | [obsws-codes]: https://github.com/obsproject/obs-websocket/blob/master/docs/generated/protocol.md#requeststatus 188 | [obsws-pro]: https://github.com/obsproject/obs-websocket/blob/master/docs/generated/protocol.md#obs-websocket-501-protocol 189 | [hatch-install]: https://hatch.pypa.io/latest/install/ 190 | -------------------------------------------------------------------------------- /examples/events/README.md: -------------------------------------------------------------------------------- 1 | ## About 2 | 3 | Registers a list of callback functions to hook into OBS events. 4 | 5 | ## Use 6 | 7 | Simply run the code and trigger the events, press `` to exit. 8 | 9 | This example assumes the existence of a `config.toml`, placed in your user home directory: 10 | 11 | ```toml 12 | [connection] 13 | host = "localhost" 14 | port = 4455 15 | password = "mystrongpass" 16 | ``` 17 | 18 | Closing OBS ends the script. 19 | -------------------------------------------------------------------------------- /examples/events/__main__.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | import obsws_python as obs 4 | 5 | 6 | class Observer: 7 | def __init__(self): 8 | self._client = obs.EventClient() 9 | self._client.callback.register( 10 | [ 11 | self.on_current_program_scene_changed, 12 | self.on_scene_created, 13 | self.on_input_mute_state_changed, 14 | self.on_exit_started, 15 | ] 16 | ) 17 | print(f"Registered events: {self._client.callback.get()}") 18 | self.running = True 19 | 20 | def __enter__(self): 21 | return self 22 | 23 | def __exit__(self, exc_type, exc_value, exc_traceback): 24 | self._client.disconnect() 25 | 26 | def on_current_program_scene_changed(self, data): 27 | """The current program scene has changed.""" 28 | print(f"Switched to scene {data.scene_name}") 29 | 30 | def on_scene_created(self, data): 31 | """A new scene has been created.""" 32 | print(f"scene {data.scene_name} has been created") 33 | 34 | def on_input_mute_state_changed(self, data): 35 | """An input's mute state has changed.""" 36 | print(f"{data.input_name} mute toggled") 37 | 38 | def on_exit_started(self, _): 39 | """OBS has begun the shutdown process.""" 40 | print("OBS closing!") 41 | self.running = False 42 | 43 | 44 | if __name__ == "__main__": 45 | with Observer() as observer: 46 | while observer.running: 47 | time.sleep(0.1) 48 | -------------------------------------------------------------------------------- /examples/hotkeys/README.md: -------------------------------------------------------------------------------- 1 | ## About 2 | 3 | Sets up some hotkeys to trigger certain actions. Registers a callback function to notify of scene switch event. 4 | 5 | Requires [Python Keyboard library](https://github.com/boppreh/keyboard). 6 | 7 | ## Use 8 | 9 | Simply run the code and press the assigned hotkeys. Press `ctrl+enter` to exit. 10 | 11 | This example assumes the existence of a `config.toml`, placed in your user home directory: 12 | 13 | ```toml 14 | [connection] 15 | host = "localhost" 16 | port = 4455 17 | password = "mystrongpass" 18 | ``` 19 | 20 | It also assumes the existence of scenes named `START`, `BRB` and `END`. 21 | -------------------------------------------------------------------------------- /examples/hotkeys/__main__.py: -------------------------------------------------------------------------------- 1 | import inspect 2 | 3 | import keyboard 4 | 5 | import obsws_python as obs 6 | 7 | 8 | class Observer: 9 | def __init__(self): 10 | self._client = obs.EventClient() 11 | self._client.callback.register(self.on_current_program_scene_changed) 12 | print(f"Registered events: {self._client.callback.get()}") 13 | 14 | def __enter__(self): 15 | return self 16 | 17 | def __exit__(self, exc_type, exc_value, exc_traceback): 18 | self._client.disconnect() 19 | 20 | @property 21 | def event_identifier(self): 22 | return inspect.stack()[1].function 23 | 24 | def on_current_program_scene_changed(self, data): 25 | """The current program scene has changed.""" 26 | print(f"{self.event_identifier}: {data.scene_name}") 27 | 28 | 29 | def version(): 30 | resp = req_client.get_version() 31 | print( 32 | f"Running OBS version:{resp.obs_version} with websocket version:{resp.obs_web_socket_version}" 33 | ) 34 | 35 | 36 | def set_scene(scene, *args): 37 | req_client.set_current_program_scene(scene) 38 | 39 | 40 | if __name__ == "__main__": 41 | with obs.ReqClient() as req_client: 42 | with Observer() as observer: 43 | keyboard.add_hotkey("0", version) 44 | keyboard.add_hotkey("1", set_scene, args=("START",)) 45 | keyboard.add_hotkey("2", set_scene, args=("BRB",)) 46 | keyboard.add_hotkey("3", set_scene, args=("END",)) 47 | 48 | print("press ctrl+enter to quit") 49 | keyboard.wait("ctrl+enter") 50 | -------------------------------------------------------------------------------- /examples/hotkeys/setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup( 4 | name="hotkeys", 5 | description="hotkeys example", 6 | install_requires=["obsws-python", "keyboard"], 7 | ) 8 | -------------------------------------------------------------------------------- /examples/levels/README.md: -------------------------------------------------------------------------------- 1 | ## About 2 | 3 | Prints POSTFADER level values for audio device `Desktop Audio`. If mute toggled prints mute state changed notification. 4 | 5 | ## Use 6 | 7 | This example assumes the existence of a `config.toml`, placed in your user home directory: 8 | 9 | ```toml 10 | [connection] 11 | host = "localhost" 12 | port = 4455 13 | password = "mystrongpass" 14 | ``` 15 | 16 | Press `` to exit from the script. 17 | -------------------------------------------------------------------------------- /examples/levels/__main__.py: -------------------------------------------------------------------------------- 1 | from enum import IntEnum 2 | from math import log 3 | 4 | import obsws_python as obs 5 | 6 | LEVELTYPE = IntEnum( 7 | "LEVELTYPE", 8 | "VU POSTFADER PREFADER", 9 | start=0, 10 | ) 11 | 12 | DEVICE = "Desktop Audio" 13 | 14 | 15 | def on_input_mute_state_changed(data): 16 | """An input's mute state has changed.""" 17 | if data.input_name == DEVICE: 18 | print(f"{DEVICE} mute toggled") 19 | 20 | 21 | def on_input_volume_meters(data): 22 | """volume level update every 50 milliseconds""" 23 | 24 | def fget(x): 25 | return round(20 * log(x, 10), 1) if x > 0 else -200.0 26 | 27 | for device in data.inputs: 28 | name = device["inputName"] 29 | if name == DEVICE and device["inputLevelsMul"]: 30 | left, right = device["inputLevelsMul"] 31 | print( 32 | f"{name} [L: {fget(left[LEVELTYPE.POSTFADER])}, R: {fget(right[LEVELTYPE.POSTFADER])}]", 33 | ) 34 | 35 | 36 | def main(): 37 | with obs.EventClient( 38 | subs=(obs.Subs.LOW_VOLUME | obs.Subs.INPUTVOLUMEMETERS) 39 | ) as client: 40 | client.callback.register([on_input_volume_meters, on_input_mute_state_changed]) 41 | 42 | while _ := input("Press to exit\n"): 43 | pass 44 | 45 | 46 | if __name__ == "__main__": 47 | main() 48 | -------------------------------------------------------------------------------- /examples/scene_rotate/README.md: -------------------------------------------------------------------------------- 1 | ## About 2 | 3 | Collects the names of all available scenes, rotates through them and prints their name. 4 | 5 | ## Use 6 | 7 | This example assumes the existence of a `config.toml`, placed in your user home directory: 8 | 9 | ```toml 10 | [connection] 11 | host = "localhost" 12 | port = 4455 13 | password = "mystrongpass" 14 | ``` 15 | -------------------------------------------------------------------------------- /examples/scene_rotate/__main__.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | import obsws_python as obs 4 | 5 | 6 | def main(): 7 | with obs.ReqClient() as client: 8 | resp = client.get_scene_list() 9 | scenes = [di.get("sceneName") for di in reversed(resp.scenes)] 10 | 11 | for scene in scenes: 12 | print(f"Switching to scene {scene}") 13 | client.set_current_program_scene(scene) 14 | time.sleep(0.5) 15 | 16 | 17 | if __name__ == "__main__": 18 | main() 19 | -------------------------------------------------------------------------------- /obsws_python/__init__.py: -------------------------------------------------------------------------------- 1 | from .events import EventClient 2 | from .reqs import ReqClient 3 | from .subs import Subs 4 | from .version import version as __version__ 5 | 6 | __ALL__ = ["ReqClient", "EventClient", "Subs"] 7 | -------------------------------------------------------------------------------- /obsws_python/baseclient.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import hashlib 3 | import json 4 | import logging 5 | from pathlib import Path 6 | from random import randint 7 | from typing import Optional 8 | 9 | import websocket 10 | from websocket import WebSocketTimeoutException 11 | 12 | from .error import OBSSDKError, OBSSDKTimeoutError 13 | 14 | logger = logging.getLogger(__name__) 15 | 16 | 17 | class ObsClient: 18 | def __init__(self, **kwargs): 19 | self.logger = logger.getChild(self.__class__.__name__) 20 | defaultkwargs = { 21 | "host": "localhost", 22 | "port": 4455, 23 | "password": "", 24 | "subs": 0, 25 | "timeout": None, 26 | } 27 | if not any(key in kwargs for key in ("host", "port", "password")): 28 | kwargs |= self._conn_from_toml() 29 | kwargs = defaultkwargs | kwargs 30 | for attr, val in kwargs.items(): 31 | setattr(self, attr, val) 32 | 33 | self.logger.info( 34 | "Connecting with parameters: host='{host}' port={port} password='{password}' subs={subs} timeout={timeout}".format( 35 | **self.__dict__ 36 | ) 37 | ) 38 | 39 | try: 40 | self.ws = websocket.WebSocket() 41 | self.ws.connect(f"ws://{self.host}:{self.port}", timeout=self.timeout) 42 | self.server_hello = json.loads(self.ws.recv()) 43 | except ValueError as e: 44 | self.logger.error(f"{type(e).__name__}: {e}") 45 | raise 46 | except (ConnectionRefusedError, TimeoutError, WebSocketTimeoutException) as e: 47 | self.logger.exception(f"{type(e).__name__}: {e}") 48 | raise 49 | 50 | def _conn_from_toml(self) -> dict: 51 | try: 52 | import tomllib 53 | except ModuleNotFoundError: 54 | import tomli as tomllib 55 | 56 | def get_filepath() -> Optional[Path]: 57 | """ 58 | traverses a list of paths for a 'config.toml' 59 | returns the first config file found or None. 60 | """ 61 | filepaths = [ 62 | Path.cwd() / "config.toml", 63 | Path.home() / "config.toml", 64 | Path.home() / ".config" / "obsws-python" / "config.toml", 65 | ] 66 | for filepath in filepaths: 67 | if filepath.exists(): 68 | return filepath 69 | 70 | conn = {} 71 | if filepath := get_filepath(): 72 | with open(filepath, "rb") as f: 73 | conn = tomllib.load(f) 74 | self.logger.info(f"loading config from {filepath}") 75 | return conn["connection"] if "connection" in conn else conn 76 | 77 | def authenticate(self): 78 | payload = { 79 | "op": 1, 80 | "d": { 81 | "rpcVersion": 1, 82 | "eventSubscriptions": self.subs, 83 | }, 84 | } 85 | 86 | if "authentication" in self.server_hello["d"]: 87 | if not self.password: 88 | raise OBSSDKError("authentication enabled but no password provided") 89 | secret = base64.b64encode( 90 | hashlib.sha256( 91 | ( 92 | self.password + self.server_hello["d"]["authentication"]["salt"] 93 | ).encode() 94 | ).digest() 95 | ) 96 | 97 | auth = base64.b64encode( 98 | hashlib.sha256( 99 | secret 100 | + self.server_hello["d"]["authentication"]["challenge"].encode() 101 | ).digest() 102 | ).decode() 103 | 104 | payload["d"]["authentication"] = auth 105 | 106 | self.ws.send(json.dumps(payload)) 107 | try: 108 | response = json.loads(self.ws.recv()) 109 | if response["op"] != 2: 110 | raise OBSSDKError( 111 | "failed to identify client with the server, expected response with OpCode 2" 112 | ) 113 | return response["d"] 114 | except json.decoder.JSONDecodeError: 115 | raise OBSSDKError( 116 | "failed to identify client with the server, please check connection settings" 117 | ) 118 | 119 | def req(self, req_type, req_data=None): 120 | payload = { 121 | "op": 6, 122 | "d": {"requestType": req_type, "requestId": randint(1, 1000)}, 123 | } 124 | if req_data: 125 | payload["d"]["requestData"] = req_data 126 | self.logger.debug(f"Sending request {payload}") 127 | try: 128 | self.ws.send(json.dumps(payload)) 129 | response = json.loads(self.ws.recv()) 130 | except WebSocketTimeoutException as e: 131 | self.logger.exception(f"{type(e).__name__}: {e}") 132 | raise OBSSDKTimeoutError("Timeout while trying to send the request") from e 133 | self.logger.debug(f"Response received {response}") 134 | return response["d"] 135 | -------------------------------------------------------------------------------- /obsws_python/callback.py: -------------------------------------------------------------------------------- 1 | from collections.abc import Callable, Iterable 2 | from typing import Union 3 | 4 | from .util import as_dataclass, to_camel_case, to_snake_case 5 | 6 | 7 | class Callback: 8 | """Adds support for callbacks""" 9 | 10 | def __init__(self): 11 | """list of current callbacks""" 12 | 13 | self._callbacks = list() 14 | 15 | def get(self) -> list: 16 | """returns a list of registered events""" 17 | 18 | return [to_camel_case(fn.__name__[2:]) for fn in self._callbacks] 19 | 20 | def trigger(self, event, data): 21 | """trigger callback on event""" 22 | 23 | for fn in self._callbacks: 24 | if fn.__name__ == f"on_{to_snake_case(event)}": 25 | fn(as_dataclass(event, data)) 26 | 27 | def register(self, fns: Union[Iterable, Callable]): 28 | """registers callback functions""" 29 | 30 | try: 31 | iterator = iter(fns) 32 | for fn in iterator: 33 | if fn not in self._callbacks: 34 | self._callbacks.append(fn) 35 | except TypeError: 36 | if fns not in self._callbacks: 37 | self._callbacks.append(fns) 38 | 39 | def deregister(self, fns: Union[Iterable, Callable]): 40 | """deregisters callback functions""" 41 | 42 | try: 43 | iterator = iter(fns) 44 | for fn in iterator: 45 | if fn in self._callbacks: 46 | self._callbacks.remove(fn) 47 | except TypeError: 48 | if fns in self._callbacks: 49 | self._callbacks.remove(fns) 50 | 51 | def clear(self): 52 | """clears the _callbacks list""" 53 | 54 | self._callbacks.clear() 55 | -------------------------------------------------------------------------------- /obsws_python/error.py: -------------------------------------------------------------------------------- 1 | class OBSSDKError(Exception): 2 | """Base class for OBSSDK errors""" 3 | 4 | 5 | class OBSSDKTimeoutError(OBSSDKError): 6 | """Exception raised when a connection times out""" 7 | 8 | 9 | class OBSSDKRequestError(OBSSDKError): 10 | """Exception raised when a request returns an error code""" 11 | 12 | def __init__(self, req_name, code, comment): 13 | self.req_name = req_name 14 | self.code = code 15 | message = f"Request {self.req_name} returned code {self.code}." 16 | if comment: 17 | message += f" With message: {comment}" 18 | super().__init__(message) 19 | -------------------------------------------------------------------------------- /obsws_python/events.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | import threading 4 | 5 | from websocket import WebSocketConnectionClosedException, WebSocketTimeoutException 6 | 7 | from .baseclient import ObsClient 8 | from .callback import Callback 9 | from .error import OBSSDKError, OBSSDKTimeoutError 10 | from .subs import Subs 11 | 12 | """ 13 | A class to interact with obs-websocket events 14 | defined in official github repo 15 | https://github.com/obsproject/obs-websocket/blob/master/docs/generated/protocol.md#events 16 | """ 17 | 18 | logger = logging.getLogger(__name__) 19 | 20 | 21 | class EventClient: 22 | def __init__(self, **kwargs): 23 | self.logger = logger.getChild(self.__class__.__name__) 24 | defaultkwargs = {"subs": Subs.LOW_VOLUME} 25 | kwargs = defaultkwargs | kwargs 26 | self.base_client = ObsClient(**kwargs) 27 | try: 28 | success = self.base_client.authenticate() 29 | self.logger.info( 30 | f"Successfully identified {self} with the server using RPC version:{success['negotiatedRpcVersion']}" 31 | ) 32 | except OBSSDKError as e: 33 | self.logger.error(f"{type(e).__name__}: {e}") 34 | raise 35 | self.callback = Callback() 36 | self.subscribe() 37 | 38 | def __enter__(self): 39 | return self 40 | 41 | def __exit__(self, exc_type, exc_value, exc_traceback): 42 | self.disconnect() 43 | 44 | def __repr__(self): 45 | return type( 46 | self 47 | ).__name__ + "(host='{host}', port={port}, password='{password}', subs={subs}, timeout={timeout})".format( 48 | **self.base_client.__dict__, 49 | ) 50 | 51 | def __str__(self): 52 | return type(self).__name__ 53 | 54 | def subscribe(self): 55 | self.base_client.ws.settimeout(None) 56 | stop_event = threading.Event() 57 | self.worker = threading.Thread( 58 | target=self.trigger, daemon=True, args=(stop_event,) 59 | ) 60 | self.worker.start() 61 | 62 | def trigger(self, stop_event): 63 | """ 64 | Continuously listen for events. 65 | 66 | Triggers a callback on event received. 67 | """ 68 | while not stop_event.is_set(): 69 | try: 70 | if response := self.base_client.ws.recv(): 71 | event = json.loads(response) 72 | self.logger.debug(f"Event received {event}") 73 | type_, data = ( 74 | event["d"].get("eventType"), 75 | event["d"].get("eventData"), 76 | ) 77 | self.callback.trigger(type_, data if data else {}) 78 | except WebSocketTimeoutException as e: 79 | self.logger.exception(f"{type(e).__name__}: {e}") 80 | raise OBSSDKTimeoutError("Timeout while waiting for event") from e 81 | except (WebSocketConnectionClosedException, OSError) as e: 82 | self.logger.debug(f"{type(e).__name__} terminating the event thread") 83 | stop_event.set() 84 | 85 | def disconnect(self): 86 | """stop listening for events""" 87 | 88 | self.base_client.ws.close() 89 | self.worker.join() 90 | 91 | unsubscribe = disconnect 92 | -------------------------------------------------------------------------------- /obsws_python/reqs.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from warnings import warn 3 | 4 | from .baseclient import ObsClient 5 | from .error import OBSSDKError, OBSSDKRequestError 6 | from .util import as_dataclass 7 | 8 | """ 9 | A class to interact with obs-websocket requests 10 | defined in official github repo 11 | https://github.com/obsproject/obs-websocket/blob/master/docs/generated/protocol.md#Requests 12 | """ 13 | 14 | logger = logging.getLogger(__name__) 15 | 16 | 17 | class ReqClient: 18 | def __init__(self, **kwargs): 19 | self.logger = logger.getChild(self.__class__.__name__) 20 | self.base_client = ObsClient(**kwargs) 21 | try: 22 | success = self.base_client.authenticate() 23 | self.logger.info( 24 | f"Successfully identified {self} with the server using RPC version:{success['negotiatedRpcVersion']}" 25 | ) 26 | except OBSSDKError as e: 27 | self.logger.error(f"{type(e).__name__}: {e}") 28 | raise 29 | 30 | def __enter__(self): 31 | return self 32 | 33 | def __exit__(self, exc_type, exc_value, exc_traceback): 34 | self.disconnect() 35 | 36 | def __repr__(self): 37 | return type( 38 | self 39 | ).__name__ + "(host='{host}', port={port}, password='{password}', timeout={timeout})".format( 40 | **self.base_client.__dict__, 41 | ) 42 | 43 | def __str__(self): 44 | return type(self).__name__ 45 | 46 | def disconnect(self): 47 | self.base_client.ws.close() 48 | 49 | def send(self, param, data=None, raw=False): 50 | try: 51 | response = self.base_client.req(param, data) 52 | if not response["requestStatus"]["result"]: 53 | raise OBSSDKRequestError( 54 | response["requestType"], 55 | response["requestStatus"]["code"], 56 | response["requestStatus"].get("comment"), 57 | ) 58 | except OBSSDKRequestError as e: 59 | self.logger.exception(f"{type(e).__name__}: {e}") 60 | raise 61 | if "responseData" in response: 62 | if raw: 63 | return response["responseData"] 64 | return as_dataclass(response["requestType"], response["responseData"]) 65 | 66 | def get_version(self): 67 | """ 68 | Gets data about the current plugin and RPC version. 69 | 70 | :return: The version info as a dictionary 71 | :rtype: dict 72 | 73 | 74 | """ 75 | return self.send("GetVersion") 76 | 77 | def get_stats(self): 78 | """ 79 | Gets statistics about OBS, obs-websocket, and the current session. 80 | 81 | :return: The stats info as a dictionary 82 | :rtype: dict 83 | 84 | 85 | """ 86 | return self.send("GetStats") 87 | 88 | def broadcast_custom_event(self, eventData): 89 | """ 90 | Broadcasts a CustomEvent to all WebSocket clients. Receivers are clients which are identified and subscribed. 91 | 92 | :param eventData: Data payload to emit to all receivers 93 | :type eventData: object 94 | :return: empty response 95 | :rtype: str 96 | 97 | 98 | """ 99 | self.send("BroadcastCustomEvent", eventData) 100 | 101 | def call_vendor_request(self, vendor_name, request_type, request_data=None): 102 | """ 103 | Call a request registered to a vendor. 104 | 105 | A vendor is a unique name registered by a 106 | third-party plugin or script, which allows 107 | for custom requests and events to be added 108 | to obs-websocket. If a plugin or script 109 | implements vendor requests or events, 110 | documentation is expected to be provided with them. 111 | 112 | :param vendorName: Name of the vendor to use 113 | :type vendorName: str 114 | :param requestType: The request type to call 115 | :type requestType: str 116 | :param requestData: Object containing appropriate request data 117 | :type requestData: dict, optional 118 | :return: responseData 119 | :rtype: dict 120 | 121 | 122 | """ 123 | payload = {"vendorName": vendor_name, "requestType": request_type} 124 | if request_data: 125 | payload["requestData"] = request_data 126 | return self.send("CallVendorRequest", payload) 127 | 128 | def get_hot_key_list(self): 129 | """ 130 | Gets an array of all hotkey names in OBS 131 | 132 | :return: hotkeys 133 | :rtype: list[str] 134 | 135 | 136 | """ 137 | return self.send("GetHotkeyList") 138 | 139 | get_hotkey_list = get_hot_key_list 140 | 141 | def trigger_hot_key_by_name(self, hotkeyName, contextName=None): 142 | """ 143 | Triggers a hotkey using its name. For hotkey names 144 | See GetHotkeyList 145 | 146 | :param hotkeyName: Name of the hotkey to trigger 147 | :type hotkeyName: str 148 | :param contextName: Name of context of the hotkey to trigger 149 | :type contextName: str, optional 150 | 151 | 152 | """ 153 | payload = {"hotkeyName": hotkeyName, "contextName": contextName} 154 | self.send("TriggerHotkeyByName", payload) 155 | 156 | trigger_hotkey_by_name = trigger_hot_key_by_name 157 | 158 | def trigger_hot_key_by_key_sequence( 159 | self, keyId, pressShift=None, pressCtrl=None, pressAlt=None, pressCmd=None 160 | ): 161 | """ 162 | Triggers a hotkey using a sequence of keys. 163 | 164 | :param keyId: The OBS key ID to use. See https://github.com/obsproject/obs-studio/blob/master/libobs/obs-hotkeys.h 165 | :type keyId: str 166 | :param pressShift: Press Shift 167 | :type pressShift: bool, optional 168 | :param pressCtrl: Press CTRL 169 | :type pressCtrl: bool, optional 170 | :param pressAlt: Press ALT 171 | :type pressAlt: bool, optional 172 | :param pressCmd: Press CMD (Mac) 173 | :type pressCmd: bool, optional 174 | 175 | 176 | """ 177 | payload = { 178 | "keyId": keyId, 179 | "keyModifiers": { 180 | "shift": pressShift, 181 | "control": pressCtrl, 182 | "alt": pressAlt, 183 | "cmd": pressCmd, 184 | }, 185 | } 186 | self.send("TriggerHotkeyByKeySequence", payload) 187 | 188 | trigger_hotkey_by_key_sequence = trigger_hot_key_by_key_sequence 189 | 190 | def sleep(self, sleepMillis=None, sleepFrames=None): 191 | """ 192 | Sleeps for a time duration or number of frames. 193 | Only available in request batches with types SERIAL_REALTIME or SERIAL_FRAME 194 | 195 | :param sleepMillis: Number of milliseconds to sleep for (if SERIAL_REALTIME mode) 0 <= sleepMillis <= 50000 196 | :type sleepMillis: int 197 | :param sleepFrames: Number of frames to sleep for (if SERIAL_FRAME mode) 0 <= sleepFrames <= 10000 198 | :type sleepFrames: int 199 | 200 | 201 | """ 202 | payload = {"sleepMillis": sleepMillis, "sleepFrames": sleepFrames} 203 | self.send("Sleep", payload) 204 | 205 | def get_persistent_data(self, realm, slotName): 206 | """ 207 | Gets the value of a "slot" from the selected persistent data realm. 208 | 209 | :param realm: The data realm to select 210 | OBS_WEBSOCKET_DATA_REALM_GLOBAL or OBS_WEBSOCKET_DATA_REALM_PROFILE 211 | :type realm: str 212 | :param slotName: The name of the slot to retrieve data from 213 | :type slotName: str 214 | :return: slotValue Value associated with the slot 215 | :rtype: any 216 | 217 | 218 | """ 219 | payload = {"realm": realm, "slotName": slotName} 220 | return self.send("GetPersistentData", payload) 221 | 222 | def set_persistent_data(self, realm, slotName, slotValue): 223 | """ 224 | Sets the value of a "slot" from the selected persistent data realm. 225 | 226 | :param realm: The data realm to select. 227 | OBS_WEBSOCKET_DATA_REALM_GLOBAL or OBS_WEBSOCKET_DATA_REALM_PROFILE 228 | :type realm: str 229 | :param slotName: The name of the slot to retrieve data from 230 | :type slotName: str 231 | :param slotValue: The value to apply to the slot 232 | :type slotValue: any 233 | 234 | 235 | """ 236 | payload = {"realm": realm, "slotName": slotName, "slotValue": slotValue} 237 | self.send("SetPersistentData", payload) 238 | 239 | def get_scene_collection_list(self): 240 | """ 241 | Gets an array of all scene collections 242 | 243 | :return: sceneCollections 244 | :rtype: list[str] 245 | 246 | 247 | """ 248 | return self.send("GetSceneCollectionList") 249 | 250 | def set_current_scene_collection(self, name): 251 | """ 252 | Switches to a scene collection. 253 | 254 | :param name: Name of the scene collection to switch to 255 | :type name: str 256 | 257 | 258 | """ 259 | payload = {"sceneCollectionName": name} 260 | self.send("SetCurrentSceneCollection", payload) 261 | 262 | def create_scene_collection(self, name): 263 | """ 264 | Creates a new scene collection, switching to it in the process. 265 | Note: This will block until the collection has finished changing. 266 | 267 | :param name: Name for the new scene collection 268 | :type name: str 269 | 270 | 271 | """ 272 | payload = {"sceneCollectionName": name} 273 | self.send("CreateSceneCollection", payload) 274 | 275 | def get_profile_list(self): 276 | """ 277 | Gets a list of all profiles 278 | 279 | :return: profiles (List of all profiles) 280 | :rtype: list[str] 281 | 282 | 283 | """ 284 | return self.send("GetProfileList") 285 | 286 | def set_current_profile(self, name): 287 | """ 288 | Switches to a profile 289 | 290 | :param name: Name of the profile to switch to 291 | :type name: str 292 | 293 | 294 | """ 295 | payload = {"profileName": name} 296 | self.send("SetCurrentProfile", payload) 297 | 298 | def create_profile(self, name): 299 | """ 300 | Creates a new profile, switching to it in the process 301 | 302 | :param name: Name for the new profile 303 | :type name: str 304 | 305 | 306 | """ 307 | payload = {"profileName": name} 308 | self.send("CreateProfile", payload) 309 | 310 | def remove_profile(self, name): 311 | """ 312 | Removes a profile. If the current profile is chosen, 313 | it will change to a different profile first. 314 | 315 | :param name: Name of the profile to remove 316 | :type name: str 317 | 318 | 319 | """ 320 | payload = {"profileName": name} 321 | self.send("RemoveProfile", payload) 322 | 323 | def get_profile_parameter(self, category, name): 324 | """ 325 | Gets a parameter from the current profile's configuration. 326 | 327 | :param category: Category of the parameter to get 328 | :type category: str 329 | :param name: Name of the parameter to get 330 | :type name: str 331 | 332 | :return: Value and default value for the parameter 333 | :rtype: str 334 | 335 | 336 | """ 337 | payload = {"parameterCategory": category, "parameterName": name} 338 | return self.send("GetProfileParameter", payload) 339 | 340 | def set_profile_parameter(self, category, name, value): 341 | """ 342 | Sets the value of a parameter in the current profile's configuration. 343 | 344 | :param category: Category of the parameter to set 345 | :type category: str 346 | :param name: Name of the parameter to set 347 | :type name: str 348 | :param value: Value of the parameter to set. Use null to delete 349 | :type value: str 350 | 351 | :return: Value and default value for the parameter 352 | :rtype: str 353 | 354 | 355 | """ 356 | payload = { 357 | "parameterCategory": category, 358 | "parameterName": name, 359 | "parameterValue": value, 360 | } 361 | self.send("SetProfileParameter", payload) 362 | 363 | def get_video_settings(self): 364 | """ 365 | Gets the current video settings. 366 | Note: To get the true FPS value, divide the FPS numerator by the FPS denominator. 367 | Example: 60000/1001 368 | 369 | 370 | """ 371 | return self.send("GetVideoSettings") 372 | 373 | def set_video_settings( 374 | self, numerator, denominator, base_width, base_height, out_width, out_height 375 | ): 376 | """ 377 | Sets the current video settings. 378 | Note: Fields must be specified in pairs. 379 | For example, you cannot set only baseWidth without needing to specify baseHeight. 380 | 381 | :param numerator: Numerator of the fractional FPS value >=1 382 | :type numerator: int 383 | :param denominator: Denominator of the fractional FPS value >=1 384 | :type denominator: int 385 | :param base_width: Width of the base (canvas) resolution in pixels (>= 1, <= 4096) 386 | :type base_width: int 387 | :param base_height: Height of the base (canvas) resolution in pixels (>= 1, <= 4096) 388 | :type base_height: int 389 | :param out_width: Width of the output resolution in pixels (>= 1, <= 4096) 390 | :type out_width: int 391 | :param out_height: Height of the output resolution in pixels (>= 1, <= 4096) 392 | :type out_height: int 393 | 394 | 395 | """ 396 | payload = { 397 | "fpsNumerator": numerator, 398 | "fpsDenominator": denominator, 399 | "baseWidth": base_width, 400 | "baseHeight": base_height, 401 | "outputWidth": out_width, 402 | "outputHeight": out_height, 403 | } 404 | self.send("SetVideoSettings", payload) 405 | 406 | def get_stream_service_settings(self): 407 | """ 408 | Gets the current stream service settings (stream destination). 409 | 410 | 411 | """ 412 | return self.send("GetStreamServiceSettings") 413 | 414 | def set_stream_service_settings(self, ss_type, ss_settings): 415 | """ 416 | Sets the current stream service settings (stream destination). 417 | Note: Simple RTMP settings can be set with type rtmp_custom 418 | and the settings fields server and key. 419 | 420 | :param ss_type: Type of stream service to apply. Example: rtmp_common or rtmp_custom 421 | :type ss_type: string 422 | :param ss_setting: Settings to apply to the service 423 | :type ss_setting: dict 424 | 425 | 426 | """ 427 | payload = { 428 | "streamServiceType": ss_type, 429 | "streamServiceSettings": ss_settings, 430 | } 431 | self.send("SetStreamServiceSettings", payload) 432 | 433 | def get_record_directory(self): 434 | """ 435 | Gets the current directory that the record output is set to. 436 | """ 437 | return self.send("GetRecordDirectory") 438 | 439 | def set_record_directory(self, recordDirectory): 440 | """ 441 | Sets the current directory that the record output writes files to. 442 | IMPORTANT NOTE: Requires obs websocket v5.3 or higher. 443 | 444 | :param recordDirectory: Output directory 445 | :type recordDirectory: str 446 | """ 447 | payload = { 448 | "recordDirectory": recordDirectory, 449 | } 450 | return self.send("SetRecordDirectory", payload) 451 | 452 | def get_source_active(self, name): 453 | """ 454 | Gets the active and show state of a source 455 | 456 | :param name: Name of the source to get the active state of 457 | :type name: str 458 | 459 | 460 | """ 461 | payload = {"sourceName": name} 462 | return self.send("GetSourceActive", payload) 463 | 464 | def get_source_screenshot(self, name, img_format, width, height, quality): 465 | """ 466 | Gets a Base64-encoded screenshot of a source. 467 | The imageWidth and imageHeight parameters are 468 | treated as "scale to inner", meaning the smallest ratio 469 | will be used and the aspect ratio of the original resolution is kept. 470 | If imageWidth and imageHeight are not specified, the compressed image 471 | will use the full resolution of the source. 472 | 473 | :param name: Name of the source to take a screenshot of 474 | :type name: str 475 | :param format: Image compression format to use. Use GetVersion to get compatible image formats 476 | :type format: str 477 | :param width: Width to scale the screenshot to (>= 8, <= 4096) 478 | :type width: int 479 | :param height: Height to scale the screenshot to (>= 8, <= 4096) 480 | :type height: int 481 | :param quality: Compression quality to use. 0 for high compression, 100 for uncompressed. -1 to use "default" 482 | :type quality: int 483 | 484 | 485 | """ 486 | payload = { 487 | "sourceName": name, 488 | "imageFormat": img_format, 489 | "imageWidth": width, 490 | "imageHeight": height, 491 | "imageCompressionQuality": quality, 492 | } 493 | return self.send("GetSourceScreenshot", payload) 494 | 495 | def save_source_screenshot( 496 | self, name, img_format, file_path, width, height, quality 497 | ): 498 | """ 499 | Saves a Base64-encoded screenshot of a source. 500 | The imageWidth and imageHeight parameters are 501 | treated as "scale to inner", meaning the smallest ratio 502 | will be used and the aspect ratio of the original resolution is kept. 503 | If imageWidth and imageHeight are not specified, the compressed image 504 | will use the full resolution of the source. 505 | 506 | :param name: Name of the source to take a screenshot of 507 | :type name: str 508 | :param format: Image compression format to use. Use GetVersion to get compatible image formats 509 | :type format: str 510 | :param file_path: Path to save the screenshot file to. Eg. C:\\Users\\user\\Desktop\\screenshot.png 511 | :type file_path: str 512 | :param width: Width to scale the screenshot to (>= 8, <= 4096) 513 | :type width: int 514 | :param height: Height to scale the screenshot to (>= 8, <= 4096) 515 | :type height: int 516 | :param quality: Compression quality to use. 0 for high compression, 100 for uncompressed. -1 to use "default" 517 | :type quality: int 518 | 519 | 520 | """ 521 | payload = { 522 | "sourceName": name, 523 | "imageFormat": img_format, 524 | "imageFilePath": file_path, 525 | "imageWidth": width, 526 | "imageHeight": height, 527 | "imageCompressionQuality": quality, 528 | } 529 | return self.send("SaveSourceScreenshot", payload) 530 | 531 | def get_scene_list(self): 532 | """ 533 | Gets a list of all scenes in OBS. 534 | 535 | 536 | """ 537 | return self.send("GetSceneList") 538 | 539 | def get_group_list(self): 540 | """ 541 | Gets a list of all groups in OBS. 542 | Groups in OBS are actually scenes, 543 | but renamed and modified. In obs-websocket, 544 | we treat them as scenes where we can.. 545 | 546 | 547 | """ 548 | return self.send("GetGroupList") 549 | 550 | def get_current_program_scene(self): 551 | """ 552 | Gets the current program scene. 553 | 554 | 555 | """ 556 | return self.send("GetCurrentProgramScene") 557 | 558 | def set_current_program_scene(self, name): 559 | """ 560 | Sets the current program scene 561 | 562 | :param name: Scene to set as the current program scene 563 | :type name: str 564 | 565 | 566 | """ 567 | payload = {"sceneName": name} 568 | self.send("SetCurrentProgramScene", payload) 569 | 570 | def get_current_preview_scene(self): 571 | """ 572 | Gets the current preview scene 573 | 574 | 575 | """ 576 | return self.send("GetCurrentPreviewScene") 577 | 578 | def set_current_preview_scene(self, name): 579 | """ 580 | Sets the current program scene 581 | 582 | :param name: Scene to set as the current preview scene 583 | :type name: str 584 | 585 | 586 | """ 587 | payload = {"sceneName": name} 588 | self.send("SetCurrentPreviewScene", payload) 589 | 590 | def create_scene(self, name): 591 | """ 592 | Creates a new scene in OBS. 593 | 594 | :param name: Name for the new scene 595 | :type name: str 596 | 597 | 598 | """ 599 | payload = {"sceneName": name} 600 | self.send("CreateScene", payload) 601 | 602 | def remove_scene(self, name): 603 | """ 604 | Removes a scene from OBS 605 | 606 | :param name: Name of the scene to remove 607 | :type name: str 608 | 609 | 610 | """ 611 | payload = {"sceneName": name} 612 | self.send("RemoveScene", payload) 613 | 614 | def set_scene_name(self, old_name, new_name): 615 | """ 616 | Sets the name of a scene (rename). 617 | 618 | :param old_name: Name of the scene to be renamed 619 | :type old_name: str 620 | :param new_name: New name for the scene 621 | :type new_name: str 622 | 623 | 624 | """ 625 | payload = {"sceneName": old_name, "newSceneName": new_name} 626 | self.send("SetSceneName", payload) 627 | 628 | def get_scene_scene_transition_override(self, name): 629 | """ 630 | Gets the scene transition overridden for a scene. 631 | 632 | :param name: Name of the scene 633 | :type name: str 634 | 635 | 636 | """ 637 | payload = {"sceneName": name} 638 | return self.send("GetSceneSceneTransitionOverride", payload) 639 | 640 | def set_scene_scene_transition_override(self, scene_name, tr_name, tr_duration): 641 | """ 642 | Gets the scene transition overridden for a scene. 643 | 644 | :param scene_name: Name of the scene 645 | :type scene_name: str 646 | :param tr_name: Name of the scene transition to use as override. Specify null to remove 647 | :type tr_name: str 648 | :param tr_duration: Duration to use for any overridden transition. Specify null to remove (>= 50, <= 20000) 649 | :type tr_duration: int 650 | 651 | 652 | """ 653 | payload = { 654 | "sceneName": scene_name, 655 | "transitionName": tr_name, 656 | "transitionDuration": tr_duration, 657 | } 658 | self.send("SetSceneSceneTransitionOverride", payload) 659 | 660 | def get_input_list(self, kind=None): 661 | """ 662 | Gets a list of all inputs in OBS. 663 | 664 | :param kind: Restrict the list to only inputs of the specified kind 665 | :type kind: str 666 | 667 | 668 | """ 669 | payload = {"inputKind": kind} 670 | return self.send("GetInputList", payload) 671 | 672 | def get_input_kind_list(self, unversioned): 673 | """ 674 | Gets a list of all available input kinds in OBS. 675 | 676 | :param unversioned: True == Return all kinds as unversioned, False == Return with version suffixes (if available) 677 | :type unversioned: bool 678 | 679 | 680 | """ 681 | payload = {"unversioned": unversioned} 682 | return self.send("GetInputKindList", payload) 683 | 684 | def get_special_inputs(self): 685 | """ 686 | Gets the name of all special inputs. 687 | 688 | 689 | """ 690 | return self.send("GetSpecialInputs") 691 | 692 | def create_input( 693 | self, sceneName, inputName, inputKind, inputSettings, sceneItemEnabled 694 | ): 695 | """ 696 | Creates a new input, adding it as a scene item to the specified scene. 697 | 698 | :param sceneName: Name of the scene to add the input to as a scene item 699 | :type sceneName: str 700 | :param inputName Name of the new input to created 701 | :type inputName: str 702 | :param inputKind: The kind of input to be created 703 | :type inputKind: str 704 | :param inputSettings: Settings object to initialize the input with 705 | :type inputSettings: object 706 | :param sceneItemEnabled: Whether to set the created scene item to enabled or disabled 707 | :type sceneItemEnabled: bool 708 | 709 | 710 | """ 711 | payload = { 712 | "sceneName": sceneName, 713 | "inputName": inputName, 714 | "inputKind": inputKind, 715 | "inputSettings": inputSettings, 716 | "sceneItemEnabled": sceneItemEnabled, 717 | } 718 | return self.send("CreateInput", payload) 719 | 720 | def remove_input(self, name): 721 | """ 722 | Removes an existing input 723 | 724 | :param name: Name of the input to remove 725 | :type name: str 726 | 727 | 728 | """ 729 | payload = {"inputName": name} 730 | self.send("RemoveInput", payload) 731 | 732 | def set_input_name(self, old_name, new_name): 733 | """ 734 | Sets the name of an input (rename). 735 | 736 | :param old_name: Current input name 737 | :type old_name: str 738 | :param new_name: New name for the input 739 | :type new_name: str 740 | 741 | 742 | """ 743 | payload = {"inputName": old_name, "newInputName": new_name} 744 | self.send("SetInputName", payload) 745 | 746 | def get_input_default_settings(self, kind): 747 | """ 748 | Gets the default settings for an input kind. 749 | 750 | :param kind: Input kind to get the default settings for 751 | :type kind: str 752 | 753 | 754 | """ 755 | payload = {"inputKind": kind} 756 | return self.send("GetInputDefaultSettings", payload) 757 | 758 | def get_input_settings(self, name): 759 | """ 760 | Gets the settings of an input. 761 | Note: Does not include defaults. To create the entire settings object, 762 | overlay inputSettings over the defaultInputSettings provided by GetInputDefaultSettings. 763 | 764 | :param name: Input kind to get the default settings for 765 | :type name: str 766 | 767 | 768 | """ 769 | payload = {"inputName": name} 770 | return self.send("GetInputSettings", payload) 771 | 772 | def set_input_settings(self, name, settings, overlay): 773 | """ 774 | Sets the settings of an input. 775 | 776 | :param name: Name of the input to set the settings of 777 | :type name: str 778 | :param settings: Object of settings to apply 779 | :type settings: dict 780 | :param overlay: True == apply the settings on top of existing ones, False == reset the input to its defaults, then apply settings. 781 | :type overlay: bool 782 | 783 | 784 | """ 785 | payload = {"inputName": name, "inputSettings": settings, "overlay": overlay} 786 | self.send("SetInputSettings", payload) 787 | 788 | def get_input_mute(self, name): 789 | """ 790 | Gets the audio mute state of an input 791 | 792 | :param name: Name of input to get the mute state of 793 | :type name: str 794 | 795 | 796 | """ 797 | payload = {"inputName": name} 798 | return self.send("GetInputMute", payload) 799 | 800 | def set_input_mute(self, name, muted): 801 | """ 802 | Sets the audio mute state of an input. 803 | 804 | :param name: Name of the input to set the mute state of 805 | :type name: str 806 | :param muted: Whether to mute the input or not 807 | :type muted: bool 808 | 809 | 810 | """ 811 | payload = {"inputName": name, "inputMuted": muted} 812 | self.send("SetInputMute", payload) 813 | 814 | def toggle_input_mute(self, name): 815 | """ 816 | Toggles the audio mute state of an input. 817 | 818 | :param name: Name of the input to toggle the mute state of 819 | :type name: str 820 | 821 | 822 | """ 823 | payload = {"inputName": name} 824 | return self.send("ToggleInputMute", payload) 825 | 826 | def get_input_volume(self, name): 827 | """ 828 | Gets the current volume setting of an input. 829 | 830 | :param name: Name of the input to get the volume of 831 | :type name: str 832 | 833 | 834 | """ 835 | payload = {"inputName": name} 836 | return self.send("GetInputVolume", payload) 837 | 838 | def set_input_volume(self, name, vol_mul=None, vol_db=None): 839 | """ 840 | Sets the volume setting of an input. 841 | 842 | :param name: Name of the input to set the volume of 843 | :type name: str 844 | :param vol_mul: Volume setting in mul (>= 0, <= 20) 845 | :type vol_mul: int 846 | :param vol_db: Volume setting in dB (>= -100, <= 26) 847 | :type vol_db: int 848 | 849 | 850 | """ 851 | payload = { 852 | "inputName": name, 853 | "inputVolumeMul": vol_mul, 854 | "inputVolumeDb": vol_db, 855 | } 856 | self.send("SetInputVolume", payload) 857 | 858 | def get_input_audio_balance(self, name): 859 | """ 860 | Gets the audio balance of an input. 861 | 862 | :param name: Name of the input to get the audio balance of 863 | :type name: str 864 | 865 | 866 | """ 867 | payload = {"inputName": name} 868 | return self.send("GetInputAudioBalance", payload) 869 | 870 | def set_input_audio_balance(self, name, balance): 871 | """ 872 | Sets the audio balance of an input. 873 | 874 | :param name: Name of the input to get the audio balance of 875 | :type name: str 876 | :param balance: New audio balance value (>= 0.0, <= 1.0) 877 | :type balance: int 878 | 879 | 880 | """ 881 | payload = {"inputName": name, "inputAudioBalance": balance} 882 | self.send("SetInputAudioBalance", payload) 883 | 884 | def get_input_audio_sync_offset(self, name): 885 | """ 886 | Gets the audio sync offset of an input. 887 | 888 | :param name: Name of the input to get the audio sync offset of 889 | :type name: str 890 | 891 | 892 | """ 893 | payload = {"inputName": name} 894 | return self.send("GetInputAudioSyncOffset", payload) 895 | 896 | def set_input_audio_sync_offset(self, name, offset): 897 | """ 898 | Sets the audio sync offset of an input. 899 | 900 | :param name: Name of the input to set the audio sync offset of 901 | :type name: str 902 | :param offset: New audio sync offset in milliseconds (>= -950, <= 20000) 903 | :type offset: int 904 | 905 | 906 | """ 907 | payload = {"inputName": name, "inputAudioSyncOffset": offset} 908 | self.send("SetInputAudioSyncOffset", payload) 909 | 910 | def get_input_audio_monitor_type(self, name): 911 | """ 912 | Gets the audio monitor type of an input. 913 | 914 | The available audio monitor types are: 915 | OBS_MONITORING_TYPE_NONE 916 | OBS_MONITORING_TYPE_MONITOR_ONLY 917 | OBS_MONITORING_TYPE_MONITOR_AND_OUTPUT 918 | 919 | 920 | :param name: Name of the input to get the audio monitor type of 921 | :type name: str 922 | 923 | 924 | """ 925 | payload = {"inputName": name} 926 | return self.send("GetInputAudioMonitorType", payload) 927 | 928 | def set_input_audio_monitor_type(self, name, mon_type): 929 | """ 930 | Sets the audio monitor type of an input. 931 | 932 | :param name: Name of the input to set the audio monitor type of 933 | :type name: str 934 | :param mon_type: Audio monitor type 935 | :type mon_type: int 936 | 937 | 938 | """ 939 | payload = {"inputName": name, "monitorType": mon_type} 940 | self.send("SetInputAudioMonitorType", payload) 941 | 942 | def get_input_audio_tracks(self, name): 943 | """ 944 | Gets the enable state of all audio tracks of an input. 945 | 946 | :param name: Name of the input 947 | :type name: str 948 | 949 | 950 | """ 951 | payload = {"inputName": name} 952 | return self.send("GetInputAudioTracks", payload) 953 | 954 | def set_input_audio_tracks(self, name, track): 955 | """ 956 | Sets the enable state of audio tracks of an input. 957 | 958 | :param name: Name of the input 959 | :type name: str 960 | :param track: Track settings to apply 961 | :type track: int 962 | 963 | 964 | """ 965 | payload = {"inputName": name, "inputAudioTracks": track} 966 | self.send("SetInputAudioTracks", payload) 967 | 968 | def get_input_properties_list_property_items(self, input_name, prop_name): 969 | """ 970 | Gets the items of a list property from an input's properties. 971 | Note: Use this in cases where an input provides a dynamic, 972 | selectable list of items. For example, display capture, 973 | where it provides a list of available displays. 974 | 975 | :param input_name: Name of the input 976 | :type input_name: str 977 | :param prop_name: Name of the list property to get the items of 978 | :type prop_name: str 979 | 980 | 981 | """ 982 | payload = {"inputName": input_name, "propertyName": prop_name} 983 | return self.send("GetInputPropertiesListPropertyItems", payload) 984 | 985 | def press_input_properties_button(self, input_name, prop_name): 986 | """ 987 | Presses a button in the properties of an input. 988 | Note: Use this in cases where there is a button 989 | in the properties of an input that cannot be accessed in any other way. 990 | For example, browser sources, where there is a refresh button. 991 | 992 | :param input_name: Name of the input 993 | :type input_name: str 994 | :param prop_name: Name of the button property to press 995 | :type prop_name: str 996 | 997 | 998 | """ 999 | payload = {"inputName": input_name, "propertyName": prop_name} 1000 | self.send("PressInputPropertiesButton", payload) 1001 | 1002 | def get_transition_kind_list(self): 1003 | """ 1004 | Gets an array of all available transition kinds. 1005 | Similar to GetInputKindList 1006 | 1007 | 1008 | """ 1009 | return self.send("GetTransitionKindList") 1010 | 1011 | def get_scene_transition_list(self): 1012 | """ 1013 | Gets an array of all scene transitions in OBS. 1014 | 1015 | 1016 | """ 1017 | return self.send("GetSceneTransitionList") 1018 | 1019 | def get_current_scene_transition(self): 1020 | """ 1021 | Gets an array of all scene transitions in OBS. 1022 | 1023 | 1024 | """ 1025 | return self.send("GetCurrentSceneTransition") 1026 | 1027 | def set_current_scene_transition(self, name): 1028 | """ 1029 | Sets the current scene transition. 1030 | Small note: While the namespace of scene transitions is generally unique, 1031 | that uniqueness is not a guarantee as it is with other resources like inputs. 1032 | 1033 | :param name: Name of the transition to make active 1034 | :type name: str 1035 | 1036 | 1037 | """ 1038 | payload = {"transitionName": name} 1039 | self.send("SetCurrentSceneTransition", payload) 1040 | 1041 | def set_current_scene_transition_duration(self, duration): 1042 | """ 1043 | Sets the duration of the current scene transition, if it is not fixed. 1044 | 1045 | :param duration: Duration in milliseconds (>= 50, <= 20000) 1046 | :type duration: str 1047 | 1048 | 1049 | """ 1050 | payload = {"transitionDuration": duration} 1051 | self.send("SetCurrentSceneTransitionDuration", payload) 1052 | 1053 | def set_current_scene_transition_settings(self, settings, overlay=None): 1054 | """ 1055 | Sets the settings of the current scene transition. 1056 | 1057 | :param settings: Settings object to apply to the transition. Can be {} 1058 | :type settings: dict 1059 | :param overlay: Whether to overlay over the current settings or replace them 1060 | :type overlay: bool 1061 | 1062 | 1063 | """ 1064 | payload = {"transitionSettings": settings, "overlay": overlay} 1065 | self.send("SetCurrentSceneTransitionSettings", payload) 1066 | 1067 | def get_current_scene_transition_cursor(self): 1068 | """ 1069 | Gets the cursor position of the current scene transition. 1070 | Note: transitionCursor will return 1.0 when the transition is inactive. 1071 | 1072 | 1073 | """ 1074 | return self.send("GetCurrentSceneTransitionCursor") 1075 | 1076 | def trigger_studio_mode_transition(self): 1077 | """ 1078 | Triggers the current scene transition. 1079 | Same functionality as the Transition button in studio mode. 1080 | Note: Studio mode should be active. if not throws an 1081 | RequestStatus::StudioModeNotActive (506) in response 1082 | 1083 | 1084 | """ 1085 | self.send("TriggerStudioModeTransition") 1086 | 1087 | def set_t_bar_position(self, pos, release=None): 1088 | """ 1089 | Sets the position of the TBar. 1090 | Very important note: This will be deprecated 1091 | and replaced in a future version of obs-websocket. 1092 | 1093 | :param pos: New position (>= 0.0, <= 1.0) 1094 | :type pos: float 1095 | :param release: Whether to release the TBar. Only set false if you know that you will be sending another position update 1096 | :type release: bool 1097 | 1098 | 1099 | """ 1100 | payload = {"position": pos, "release": release} 1101 | self.send("SetTBarPosition", payload) 1102 | 1103 | def get_source_filter_list(self, name): 1104 | """ 1105 | Gets a list of all of a source's filters. 1106 | 1107 | :param name: Name of the source 1108 | :type name: str 1109 | 1110 | 1111 | """ 1112 | payload = {"sourceName": name} 1113 | return self.send("GetSourceFilterList", payload) 1114 | 1115 | def get_source_filter_default_settings(self, kind): 1116 | """ 1117 | Gets the default settings for a filter kind. 1118 | 1119 | :param kind: Filter kind to get the default settings for 1120 | :type kind: str 1121 | 1122 | 1123 | """ 1124 | payload = {"filterKind": kind} 1125 | return self.send("GetSourceFilterDefaultSettings", payload) 1126 | 1127 | def create_source_filter( 1128 | self, source_name, filter_name, filter_kind, filter_settings=None 1129 | ): 1130 | """ 1131 | Gets the default settings for a filter kind. 1132 | 1133 | :param source_name: Name of the source to add the filter to 1134 | :type source_name: str 1135 | :param filter_name: Name of the new filter to be created 1136 | :type filter_name: str 1137 | :param filter_kind: The kind of filter to be created 1138 | :type filter_kind: str 1139 | :param filter_settings: Settings object to initialize the filter with 1140 | :type filter_settings: dict 1141 | 1142 | 1143 | """ 1144 | payload = { 1145 | "sourceName": source_name, 1146 | "filterName": filter_name, 1147 | "filterKind": filter_kind, 1148 | "filterSettings": filter_settings, 1149 | } 1150 | self.send("CreateSourceFilter", payload) 1151 | 1152 | def remove_source_filter(self, source_name, filter_name): 1153 | """ 1154 | Gets the default settings for a filter kind. 1155 | 1156 | :param source_name: Name of the source the filter is on 1157 | :type source_name: str 1158 | :param filter_name: Name of the filter to remove 1159 | :type filter_name: str 1160 | 1161 | 1162 | """ 1163 | payload = { 1164 | "sourceName": source_name, 1165 | "filterName": filter_name, 1166 | } 1167 | self.send("RemoveSourceFilter", payload) 1168 | 1169 | def set_source_filter_name(self, source_name, old_filter_name, new_filter_name): 1170 | """ 1171 | Sets the name of a source filter (rename). 1172 | 1173 | :param source_name: Name of the source the filter is on 1174 | :type source_name: str 1175 | :param old_filter_name: Current name of the filter 1176 | :type old_filter_name: str 1177 | :param new_filter_name: New name for the filter 1178 | :type new_filter_name: str 1179 | 1180 | 1181 | """ 1182 | payload = { 1183 | "sourceName": source_name, 1184 | "filterName": old_filter_name, 1185 | "newFilterName": new_filter_name, 1186 | } 1187 | self.send("SetSourceFilterName", payload) 1188 | 1189 | def get_source_filter(self, source_name, filter_name): 1190 | """ 1191 | Gets the info for a specific source filter. 1192 | 1193 | :param source_name: Name of the source 1194 | :type source_name: str 1195 | :param filter_name: Name of the filter 1196 | :type filter_name: str 1197 | 1198 | 1199 | """ 1200 | payload = {"sourceName": source_name, "filterName": filter_name} 1201 | return self.send("GetSourceFilter", payload) 1202 | 1203 | def set_source_filter_index(self, source_name, filter_name, filter_index): 1204 | """ 1205 | Sets the index position of a filter on a source. 1206 | 1207 | :param source_name: Name of the source the filter is on 1208 | :type source_name: str 1209 | :param filter_name: Name of the filter 1210 | :type filter_name: str 1211 | :param filterIndex: New index position of the filter (>= 0) 1212 | :type filterIndex: int 1213 | 1214 | 1215 | """ 1216 | payload = { 1217 | "sourceName": source_name, 1218 | "filterName": filter_name, 1219 | "filterIndex": filter_index, 1220 | } 1221 | self.send("SetSourceFilterIndex", payload) 1222 | 1223 | def set_source_filter_settings( 1224 | self, source_name, filter_name, settings, overlay=None 1225 | ): 1226 | """ 1227 | Sets the settings of a source filter. 1228 | 1229 | :param source_name: Name of the source the filter is on 1230 | :type source_name: str 1231 | :param filter_name: Name of the filter to set the settings of 1232 | :type filter_name: str 1233 | :param settings: Dictionary of settings to apply 1234 | :type settings: dict 1235 | :param overlay: True == apply the settings on top of existing ones, False == reset the input to its defaults, then apply settings. 1236 | :type overlay: bool 1237 | 1238 | 1239 | """ 1240 | payload = { 1241 | "sourceName": source_name, 1242 | "filterName": filter_name, 1243 | "filterSettings": settings, 1244 | "overlay": overlay, 1245 | } 1246 | self.send("SetSourceFilterSettings", payload) 1247 | 1248 | def set_source_filter_enabled(self, source_name, filter_name, enabled): 1249 | """ 1250 | Sets the enable state of a source filter. 1251 | 1252 | :param source_name: Name of the source the filter is on 1253 | :type source_name: str 1254 | :param filter_name: Name of the filter 1255 | :type filter_name: str 1256 | :param enabled: New enable state of the filter 1257 | :type enabled: bool 1258 | 1259 | 1260 | """ 1261 | payload = { 1262 | "sourceName": source_name, 1263 | "filterName": filter_name, 1264 | "filterEnabled": enabled, 1265 | } 1266 | self.send("SetSourceFilterEnabled", payload) 1267 | 1268 | def get_scene_item_list(self, name): 1269 | """ 1270 | Gets a list of all scene items in a scene. 1271 | 1272 | :param name: Name of the scene to get the items of 1273 | :type name: str 1274 | 1275 | 1276 | """ 1277 | payload = {"sceneName": name} 1278 | return self.send("GetSceneItemList", payload) 1279 | 1280 | def get_group_scene_item_list(self, name): 1281 | """ 1282 | Basically GetSceneItemList, but for groups. 1283 | 1284 | Using groups at all in OBS is discouraged, as they are very broken under the hood. 1285 | 1286 | :param name: Name of the group to get the items of 1287 | :type name: str 1288 | 1289 | 1290 | """ 1291 | payload = {"sceneName": name} 1292 | return self.send("GetGroupSceneItemList", payload) 1293 | 1294 | def get_scene_item_id(self, scene_name, source_name, offset=None): 1295 | """ 1296 | Searches a scene for a source, and returns its id. 1297 | 1298 | :param scene_name: Name of the scene or group to search in 1299 | :type scene_name: str 1300 | :param source_name: Name of the source to find 1301 | :type source_name: str 1302 | :param offset: Number of matches to skip during search. >= 0 means first forward. -1 means last (top) item (>= -1) 1303 | :type offset: int 1304 | 1305 | 1306 | """ 1307 | payload = { 1308 | "sceneName": scene_name, 1309 | "sourceName": source_name, 1310 | "searchOffset": offset, 1311 | } 1312 | return self.send("GetSceneItemId", payload) 1313 | 1314 | def create_scene_item(self, scene_name, source_name, enabled=None): 1315 | """ 1316 | Creates a new scene item using a source. 1317 | Scenes only 1318 | 1319 | :param scene_name: Name of the scene to create the new item in 1320 | :type scene_name: str 1321 | :param source_name: Name of the source to add to the scene 1322 | :type source_name: str 1323 | :param enabled: Enable state to apply to the scene item on creation 1324 | :type enabled: bool 1325 | 1326 | 1327 | """ 1328 | payload = { 1329 | "sceneName": scene_name, 1330 | "sourceName": source_name, 1331 | "sceneItemEnabled": enabled, 1332 | } 1333 | return self.send("CreateSceneItem", payload) 1334 | 1335 | def remove_scene_item(self, scene_name, item_id): 1336 | """ 1337 | Removes a scene item from a scene. 1338 | Scenes only 1339 | 1340 | :param scene_name: Name of the scene the item is in 1341 | :type scene_name: str 1342 | :param item_id: Numeric ID of the scene item 1343 | :type item_id: int 1344 | 1345 | 1346 | """ 1347 | payload = { 1348 | "sceneName": scene_name, 1349 | "sceneItemId": item_id, 1350 | } 1351 | self.send("RemoveSceneItem", payload) 1352 | 1353 | def duplicate_scene_item(self, scene_name, item_id, dest_scene_name=None): 1354 | """ 1355 | Duplicates a scene item, copying all transform and crop info. 1356 | Scenes only 1357 | 1358 | :param scene_name: Name of the scene the item is in 1359 | :type scene_name: str 1360 | :param item_id: Numeric ID of the scene item (>= 0) 1361 | :type item_id: int 1362 | :param dest_scene_name: Name of the scene to create the duplicated item in 1363 | :type dest_scene_name: str 1364 | 1365 | 1366 | """ 1367 | payload = { 1368 | "sceneName": scene_name, 1369 | "sceneItemId": item_id, 1370 | "destinationSceneName": dest_scene_name, 1371 | } 1372 | return self.send("DuplicateSceneItem", payload) 1373 | 1374 | def get_scene_item_transform(self, scene_name, item_id): 1375 | """ 1376 | Gets the transform and crop info of a scene item. 1377 | Scenes and Groups 1378 | 1379 | :param scene_name: Name of the scene the item is in 1380 | :type scene_name: str 1381 | :param item_id: Numeric ID of the scene item (>= 0) 1382 | :type item_id: int 1383 | 1384 | 1385 | """ 1386 | payload = { 1387 | "sceneName": scene_name, 1388 | "sceneItemId": item_id, 1389 | } 1390 | return self.send("GetSceneItemTransform", payload) 1391 | 1392 | def set_scene_item_transform(self, scene_name, item_id, transform): 1393 | """ 1394 | Sets the transform and crop info of a scene item. 1395 | 1396 | :param scene_name: Name of the scene the item is in 1397 | :type scene_name: str 1398 | :param item_id: Numeric ID of the scene item (>= 0) 1399 | :type item_id: int 1400 | :param transform: Dictionary containing scene item transform info to update 1401 | :type transform: dict 1402 | """ 1403 | payload = { 1404 | "sceneName": scene_name, 1405 | "sceneItemId": item_id, 1406 | "sceneItemTransform": transform, 1407 | } 1408 | self.send("SetSceneItemTransform", payload) 1409 | 1410 | def get_scene_item_enabled(self, scene_name, item_id): 1411 | """ 1412 | Gets the enable state of a scene item. 1413 | Scenes and Groups 1414 | 1415 | :param scene_name: Name of the scene the item is in 1416 | :type scene_name: str 1417 | :param item_id: Numeric ID of the scene item (>= 0) 1418 | :type item_id: int 1419 | 1420 | 1421 | """ 1422 | payload = { 1423 | "sceneName": scene_name, 1424 | "sceneItemId": item_id, 1425 | } 1426 | return self.send("GetSceneItemEnabled", payload) 1427 | 1428 | def set_scene_item_enabled(self, scene_name, item_id, enabled): 1429 | """ 1430 | Sets the enable state of a scene item. 1431 | Scenes and Groups' 1432 | 1433 | :param scene_name: Name of the scene the item is in 1434 | :type scene_name: str 1435 | :param item_id: Numeric ID of the scene item (>= 0) 1436 | :type item_id: int 1437 | :param enabled: New enable state of the scene item 1438 | :type enabled: bool 1439 | 1440 | 1441 | """ 1442 | payload = { 1443 | "sceneName": scene_name, 1444 | "sceneItemId": item_id, 1445 | "sceneItemEnabled": enabled, 1446 | } 1447 | self.send("SetSceneItemEnabled", payload) 1448 | 1449 | def get_scene_item_locked(self, scene_name, item_id): 1450 | """ 1451 | Gets the lock state of a scene item. 1452 | Scenes and Groups 1453 | 1454 | :param scene_name: Name of the scene the item is in 1455 | :type scene_name: str 1456 | :param item_id: Numeric ID of the scene item (>= 0) 1457 | :type item_id: int 1458 | 1459 | 1460 | """ 1461 | payload = { 1462 | "sceneName": scene_name, 1463 | "sceneItemId": item_id, 1464 | } 1465 | return self.send("GetSceneItemLocked", payload) 1466 | 1467 | def set_scene_item_locked(self, scene_name, item_id, locked): 1468 | """ 1469 | Sets the lock state of a scene item. 1470 | Scenes and Groups 1471 | 1472 | :param scene_name: Name of the scene the item is in 1473 | :type scene_name: str 1474 | :param item_id: Numeric ID of the scene item (>= 0) 1475 | :type item_id: int 1476 | :param locked: New lock state of the scene item 1477 | :type locked: bool 1478 | 1479 | 1480 | """ 1481 | payload = { 1482 | "sceneName": scene_name, 1483 | "sceneItemId": item_id, 1484 | "sceneItemLocked": locked, 1485 | } 1486 | self.send("SetSceneItemLocked", payload) 1487 | 1488 | def get_scene_item_index(self, scene_name, item_id): 1489 | """ 1490 | Gets the index position of a scene item in a scene. 1491 | An index of 0 is at the bottom of the source list in the UI. 1492 | Scenes and Groups 1493 | 1494 | :param scene_name: Name of the scene the item is in 1495 | :type scene_name: str 1496 | :param item_id: Numeric ID of the scene item (>= 0) 1497 | :type item_id: int 1498 | 1499 | 1500 | """ 1501 | payload = { 1502 | "sceneName": scene_name, 1503 | "sceneItemId": item_id, 1504 | } 1505 | return self.send("GetSceneItemIndex", payload) 1506 | 1507 | def set_scene_item_index(self, scene_name, item_id, item_index): 1508 | """ 1509 | Sets the index position of a scene item in a scene. 1510 | Scenes and Groups 1511 | 1512 | :param scene_name: Name of the scene the item is in 1513 | :type scene_name: str 1514 | :param item_id: Numeric ID of the scene item (>= 0) 1515 | :type item_id: int 1516 | :param item_index: New index position of the scene item (>= 0) 1517 | :type item_index: int 1518 | 1519 | 1520 | """ 1521 | payload = { 1522 | "sceneName": scene_name, 1523 | "sceneItemId": item_id, 1524 | "sceneItemIndex": item_index, 1525 | } 1526 | self.send("SetSceneItemIndex", payload) 1527 | 1528 | def get_scene_item_blend_mode(self, scene_name, item_id): 1529 | """ 1530 | Gets the blend mode of a scene item. 1531 | Blend modes: 1532 | 1533 | OBS_BLEND_NORMAL 1534 | OBS_BLEND_ADDITIVE 1535 | OBS_BLEND_SUBTRACT 1536 | OBS_BLEND_SCREEN 1537 | OBS_BLEND_MULTIPLY 1538 | OBS_BLEND_LIGHTEN 1539 | OBS_BLEND_DARKEN 1540 | Scenes and Groups 1541 | 1542 | :param scene_name: Name of the scene the item is in 1543 | :type scene_name: str 1544 | :param item_id: Numeric ID of the scene item (>= 0) 1545 | :type item_id: int 1546 | 1547 | 1548 | """ 1549 | payload = { 1550 | "sceneName": scene_name, 1551 | "sceneItemId": item_id, 1552 | } 1553 | return self.send("GetSceneItemBlendMode", payload) 1554 | 1555 | def set_scene_item_blend_mode(self, scene_name, item_id, blend): 1556 | """ 1557 | Sets the blend mode of a scene item. 1558 | Scenes and Groups 1559 | 1560 | :param scene_name: Name of the scene the item is in 1561 | :type scene_name: str 1562 | :param item_id: Numeric ID of the scene item (>= 0) 1563 | :type item_id: int 1564 | :param blend: New blend mode 1565 | :type blend: str 1566 | 1567 | 1568 | """ 1569 | payload = { 1570 | "sceneName": scene_name, 1571 | "sceneItemId": item_id, 1572 | "sceneItemBlendMode": blend, 1573 | } 1574 | self.send("SetSceneItemBlendMode", payload) 1575 | 1576 | def get_virtual_cam_status(self): 1577 | """ 1578 | Gets the status of the virtualcam output. 1579 | 1580 | 1581 | """ 1582 | return self.send("GetVirtualCamStatus") 1583 | 1584 | def toggle_virtual_cam(self): 1585 | """ 1586 | Toggles the state of the virtualcam output. 1587 | 1588 | 1589 | """ 1590 | return self.send("ToggleVirtualCam") 1591 | 1592 | def start_virtual_cam(self): 1593 | """ 1594 | Starts the virtualcam output. 1595 | 1596 | 1597 | """ 1598 | self.send("StartVirtualCam") 1599 | 1600 | def stop_virtual_cam(self): 1601 | """ 1602 | Stops the virtualcam output. 1603 | 1604 | 1605 | """ 1606 | self.send("StopVirtualCam") 1607 | 1608 | def get_replay_buffer_status(self): 1609 | """ 1610 | Gets the status of the replay buffer output. 1611 | 1612 | 1613 | """ 1614 | return self.send("GetReplayBufferStatus") 1615 | 1616 | def toggle_replay_buffer(self): 1617 | """ 1618 | Toggles the state of the replay buffer output. 1619 | 1620 | 1621 | """ 1622 | return self.send("ToggleReplayBuffer") 1623 | 1624 | def start_replay_buffer(self): 1625 | """ 1626 | Starts the replay buffer output. 1627 | 1628 | 1629 | """ 1630 | self.send("StartReplayBuffer") 1631 | 1632 | def stop_replay_buffer(self): 1633 | """ 1634 | Stops the replay buffer output. 1635 | 1636 | 1637 | """ 1638 | self.send("StopReplayBuffer") 1639 | 1640 | def save_replay_buffer(self): 1641 | """ 1642 | Saves the contents of the replay buffer output. 1643 | 1644 | 1645 | """ 1646 | self.send("SaveReplayBuffer") 1647 | 1648 | def get_last_replay_buffer_replay(self): 1649 | """ 1650 | Gets the filename of the last replay buffer save file. 1651 | 1652 | 1653 | """ 1654 | return self.send("GetLastReplayBufferReplay") 1655 | 1656 | def get_output_list(self): 1657 | """ 1658 | Gets the list of available outputs. 1659 | """ 1660 | return self.send("GetOutputList") 1661 | 1662 | def get_output_status(self, name): 1663 | """ 1664 | Gets the status of an output. 1665 | 1666 | :param name: Output name 1667 | :type name: str 1668 | """ 1669 | payload = {"outputName": name} 1670 | return self.send("GetOutputStatus", payload) 1671 | 1672 | def toggle_output(self, name): 1673 | """ 1674 | Toggles the status of an output. 1675 | 1676 | :param name: Output name 1677 | :type name: str 1678 | """ 1679 | payload = {"outputName": name} 1680 | return self.send("ToggleOutput", payload) 1681 | 1682 | def start_output(self, name): 1683 | """ 1684 | Starts an output. 1685 | 1686 | :param name: Output name 1687 | :type name: str 1688 | """ 1689 | payload = {"outputName": name} 1690 | self.send("StartOutput", payload) 1691 | 1692 | def stop_output(self, name): 1693 | """ 1694 | Stops an output. 1695 | 1696 | :param name: Output name 1697 | :type name: str 1698 | """ 1699 | payload = {"outputName": name} 1700 | self.send("StopOutput", payload) 1701 | 1702 | def get_output_settings(self, name): 1703 | """ 1704 | Gets the settings of an output. 1705 | 1706 | :param name: Output name 1707 | :type name: str 1708 | """ 1709 | payload = {"outputName": name} 1710 | return self.send("GetOutputSettings", payload) 1711 | 1712 | def set_output_settings(self, name, settings): 1713 | """ 1714 | Sets the settings of an output. 1715 | 1716 | :param name: Output name 1717 | :type name: str 1718 | :param settings: Output settings 1719 | :type settings: dict 1720 | """ 1721 | payload = { 1722 | "outputName": name, 1723 | "outputSettings": settings, 1724 | } 1725 | self.send("SetOutputSettings", payload) 1726 | 1727 | def get_stream_status(self): 1728 | """ 1729 | Gets the status of the stream output. 1730 | 1731 | 1732 | """ 1733 | return self.send("GetStreamStatus") 1734 | 1735 | def toggle_stream(self): 1736 | """ 1737 | Toggles the status of the stream output. 1738 | 1739 | 1740 | """ 1741 | return self.send("ToggleStream") 1742 | 1743 | def start_stream(self): 1744 | """ 1745 | Starts the stream output. 1746 | 1747 | 1748 | """ 1749 | self.send("StartStream") 1750 | 1751 | def stop_stream(self): 1752 | """ 1753 | Stops the stream output. 1754 | 1755 | 1756 | """ 1757 | self.send("StopStream") 1758 | 1759 | def send_stream_caption(self, caption): 1760 | """ 1761 | Sends CEA-608 caption text over the stream output. 1762 | 1763 | :param caption: Caption text 1764 | :type caption: str 1765 | 1766 | 1767 | """ 1768 | payload = { 1769 | "captionText": caption, 1770 | } 1771 | self.send("SendStreamCaption", payload) 1772 | 1773 | def get_record_status(self): 1774 | """ 1775 | Gets the status of the record output. 1776 | 1777 | 1778 | """ 1779 | return self.send("GetRecordStatus") 1780 | 1781 | def toggle_record(self): 1782 | """ 1783 | Toggles the status of the record output. 1784 | 1785 | 1786 | """ 1787 | return self.send("ToggleRecord") 1788 | 1789 | def start_record(self): 1790 | """ 1791 | Starts the record output. 1792 | 1793 | 1794 | """ 1795 | self.send("StartRecord") 1796 | 1797 | def stop_record(self): 1798 | """ 1799 | Stops the record output. 1800 | 1801 | 1802 | """ 1803 | return self.send("StopRecord") 1804 | 1805 | def toggle_record_pause(self): 1806 | """ 1807 | Toggles pause on the record output. 1808 | 1809 | 1810 | """ 1811 | self.send("ToggleRecordPause") 1812 | 1813 | def pause_record(self): 1814 | """ 1815 | Pauses the record output. 1816 | 1817 | 1818 | """ 1819 | self.send("PauseRecord") 1820 | 1821 | def resume_record(self): 1822 | """ 1823 | Resumes the record output. 1824 | 1825 | 1826 | """ 1827 | self.send("ResumeRecord") 1828 | 1829 | def get_media_input_status(self, name): 1830 | """ 1831 | Gets the status of a media input. 1832 | 1833 | Media States: 1834 | OBS_MEDIA_STATE_NONE 1835 | OBS_MEDIA_STATE_PLAYING 1836 | OBS_MEDIA_STATE_OPENING 1837 | OBS_MEDIA_STATE_BUFFERING 1838 | OBS_MEDIA_STATE_PAUSED 1839 | OBS_MEDIA_STATE_STOPPED 1840 | OBS_MEDIA_STATE_ENDED 1841 | OBS_MEDIA_STATE_ERROR 1842 | 1843 | :param name: Name of the media input 1844 | :type name: str 1845 | 1846 | 1847 | """ 1848 | payload = {"inputName": name} 1849 | return self.send("GetMediaInputStatus", payload) 1850 | 1851 | def set_media_input_cursor(self, name, cursor): 1852 | """ 1853 | Sets the cursor position of a media input. 1854 | This request does not perform bounds checking of the cursor position. 1855 | 1856 | :param name: Name of the media input 1857 | :type name: str 1858 | :param cursor: New cursor position to set (>= 0) 1859 | :type cursor: int 1860 | 1861 | 1862 | """ 1863 | payload = {"inputName": name, "mediaCursor": cursor} 1864 | self.send("SetMediaInputCursor", payload) 1865 | 1866 | def offset_media_input_cursor(self, name, offset): 1867 | """ 1868 | Offsets the current cursor position of a media input by the specified value. 1869 | This request does not perform bounds checking of the cursor position. 1870 | 1871 | :param name: Name of the media input 1872 | :type name: str 1873 | :param offset: Value to offset the current cursor position by 1874 | :type offset: int 1875 | 1876 | 1877 | """ 1878 | payload = {"inputName": name, "mediaCursorOffset": offset} 1879 | self.send("OffsetMediaInputCursor", payload) 1880 | 1881 | def trigger_media_input_action(self, name, action): 1882 | """ 1883 | Triggers an action on a media input. 1884 | 1885 | :param name: Name of the media input 1886 | :type name: str 1887 | :param action: Identifier of the ObsMediaInputAction enum 1888 | :type action: str 1889 | 1890 | 1891 | """ 1892 | payload = {"inputName": name, "mediaAction": action} 1893 | self.send("TriggerMediaInputAction", payload) 1894 | 1895 | def get_studio_mode_enabled(self): 1896 | """ 1897 | Gets whether studio is enabled. 1898 | 1899 | 1900 | """ 1901 | return self.send("GetStudioModeEnabled") 1902 | 1903 | def set_studio_mode_enabled(self, enabled): 1904 | """ 1905 | Enables or disables studio mode 1906 | 1907 | :param enabled: True == Enabled, False == Disabled 1908 | :type enabled: bool 1909 | 1910 | 1911 | """ 1912 | payload = {"studioModeEnabled": enabled} 1913 | self.send("SetStudioModeEnabled", payload) 1914 | 1915 | def open_input_properties_dialog(self, name): 1916 | """ 1917 | Opens the properties dialog of an input. 1918 | 1919 | :param name: Name of the input to open the dialog of 1920 | :type name: str 1921 | 1922 | 1923 | """ 1924 | payload = {"inputName": name} 1925 | self.send("OpenInputPropertiesDialog", payload) 1926 | 1927 | def open_input_filters_dialog(self, name): 1928 | """ 1929 | Opens the filters dialog of an input. 1930 | 1931 | :param name: Name of the input to open the dialog of 1932 | :type name: str 1933 | 1934 | 1935 | """ 1936 | payload = {"inputName": name} 1937 | self.send("OpenInputFiltersDialog", payload) 1938 | 1939 | def open_input_interact_dialog(self, name): 1940 | """ 1941 | Opens the filters dialog of an input. 1942 | 1943 | :param name: Name of the input to open the dialog of 1944 | :type name: str 1945 | 1946 | 1947 | """ 1948 | payload = {"inputName": name} 1949 | self.send("OpenInputInteractDialog", payload) 1950 | 1951 | def get_monitor_list(self): 1952 | """ 1953 | Gets a list of connected monitors and information about them. 1954 | 1955 | 1956 | """ 1957 | return self.send("GetMonitorList") 1958 | 1959 | def open_video_mix_projector( 1960 | self, video_mix_type, monitor_index=-1, projector_geometry=None 1961 | ): 1962 | """ 1963 | Opens a projector for a specific output video mix. 1964 | 1965 | The available mix types are: 1966 | OBS_WEBSOCKET_VIDEO_MIX_TYPE_PREVIEW 1967 | OBS_WEBSOCKET_VIDEO_MIX_TYPE_PROGRAM 1968 | OBS_WEBSOCKET_VIDEO_MIX_TYPE_MULTIVIEW 1969 | 1970 | :param video_mix_type: Type of mix to open. 1971 | :type video_mix_type: str 1972 | :param monitor_index: Monitor index, use GetMonitorList to obtain index 1973 | :type monitor_index: int 1974 | :param projector_geometry: 1975 | Size/Position data for a windowed projector, in Qt Base64 encoded format. 1976 | Mutually exclusive with monitorIndex 1977 | :type projector_geometry: str 1978 | 1979 | """ 1980 | warn( 1981 | "open_video_mix_projector request serves to provide feature parity with 4.x. " 1982 | "It is very likely to be changed/deprecated in a future release.", 1983 | DeprecationWarning, 1984 | stacklevel=2, 1985 | ) 1986 | payload = { 1987 | "videoMixType": video_mix_type, 1988 | "monitorIndex": monitor_index, 1989 | "projectorGeometry": projector_geometry, 1990 | } 1991 | self.send("OpenVideoMixProjector", payload) 1992 | 1993 | def open_source_projector( 1994 | self, source_name, monitor_index=-1, projector_geometry=None 1995 | ): 1996 | """ 1997 | Opens a projector for a source. 1998 | 1999 | :param source_name: Name of the source to open a projector for 2000 | :type source_name: str 2001 | :param monitor_index: Monitor index, use GetMonitorList to obtain index 2002 | :type monitor_index: int 2003 | :param projector_geometry: 2004 | Size/Position data for a windowed projector, in Qt Base64 encoded format. 2005 | Mutually exclusive with monitorIndex 2006 | :type projector_geometry: str 2007 | 2008 | """ 2009 | warn( 2010 | "open_source_projector request serves to provide feature parity with 4.x. " 2011 | "It is very likely to be changed/deprecated in a future release.", 2012 | DeprecationWarning, 2013 | stacklevel=2, 2014 | ) 2015 | payload = { 2016 | "sourceName": source_name, 2017 | "monitorIndex": monitor_index, 2018 | "projectorGeometry": projector_geometry, 2019 | } 2020 | self.send("OpenSourceProjector", payload) 2021 | -------------------------------------------------------------------------------- /obsws_python/subs.py: -------------------------------------------------------------------------------- 1 | from enum import IntFlag 2 | 3 | 4 | class Subs(IntFlag): 5 | GENERAL = 1 << 0 6 | CONFIG = 1 << 1 7 | SCENES = 1 << 2 8 | INPUTS = 1 << 3 9 | TRANSITIONS = 1 << 4 10 | FILTERS = 1 << 5 11 | OUTPUTS = 1 << 6 12 | SCENEITEMS = 1 << 7 13 | MEDIAINPUTS = 1 << 8 14 | VENDORS = 1 << 9 15 | UI = 1 << 10 16 | 17 | LOW_VOLUME = ( 18 | GENERAL 19 | | CONFIG 20 | | SCENES 21 | | INPUTS 22 | | TRANSITIONS 23 | | FILTERS 24 | | OUTPUTS 25 | | SCENEITEMS 26 | | MEDIAINPUTS 27 | | VENDORS 28 | | UI 29 | ) 30 | 31 | INPUTVOLUMEMETERS = 1 << 16 32 | INPUTACTIVESTATECHANGED = 1 << 17 33 | INPUTSHOWSTATECHANGED = 1 << 18 34 | SCENEITEMTRANSFORMCHANGED = 1 << 19 35 | 36 | HIGH_VOLUME = ( 37 | INPUTVOLUMEMETERS 38 | | INPUTACTIVESTATECHANGED 39 | | INPUTSHOWSTATECHANGED 40 | | SCENEITEMTRANSFORMCHANGED 41 | ) 42 | 43 | ALL = LOW_VOLUME | HIGH_VOLUME 44 | -------------------------------------------------------------------------------- /obsws_python/util.py: -------------------------------------------------------------------------------- 1 | import re 2 | from dataclasses import dataclass 3 | 4 | 5 | def to_camel_case(s): 6 | return "".join(word.title() for word in s.split("_")) 7 | 8 | 9 | def to_snake_case(s): 10 | return re.sub(r"(?=3.9" 12 | authors = [ 13 | { name = "Adem Atikturk", email = "aatikturk@gmail.com" }, 14 | ] 15 | dependencies = [ 16 | "tomli >= 2.0.1;python_version < '3.11'", 17 | "websocket-client", 18 | ] 19 | 20 | [project.urls] 21 | Homepage = "https://github.com/aatikturk/obsws-python" 22 | 23 | [tool.hatch.version] 24 | path = "obsws_python/version.py" 25 | 26 | [tool.hatch.build.targets.sdist] 27 | include = [ 28 | "/obsws_python", 29 | ] 30 | 31 | [tool.hatch.envs.default] 32 | dependencies = ["pre-commit"] 33 | 34 | [tool.hatch.envs.e] 35 | dependencies = ["keyboard"] 36 | 37 | [tool.hatch.envs.e.scripts] 38 | events = "python {root}\\examples\\events\\." 39 | hotkeys = "python {root}\\examples\\hotkeys\\." 40 | levels = "python {root}\\examples\\levels\\." 41 | scene_rotate = "python {root}\\examples\\scene_rotate\\." 42 | 43 | [tool.hatch.envs.hatch-test] 44 | randomize = true 45 | 46 | [tool.hatch.envs.hatch-test.scripts] 47 | run = "pytest{env:HATCH_TEST_ARGS:} {args}" 48 | 49 | [[tool.hatch.envs.hatch-test.matrix]] 50 | python = ["313", "312", "311", "310", "39"] 51 | 52 | [tool.hatch.envs.style] 53 | detached = true 54 | dependencies = [ 55 | "black", 56 | "isort", 57 | ] 58 | 59 | [tool.hatch.envs.style.scripts] 60 | check = [ 61 | "black --check --diff .", 62 | "isort --check-only --diff .", 63 | ] 64 | fmt = [ 65 | "isort .", 66 | "black .", 67 | ] 68 | 69 | [tool.black] 70 | line-length = 88 71 | include = '\.pyi?$' 72 | # 'extend-exclude' excludes files or directories in addition to the defaults 73 | extend-exclude = ''' 74 | ( 75 | ^/\.git/ # exclude all files in the .git directory 76 | ^/\.hatch/ # exclude all files in the .hatch directory 77 | ^/\.pytest_cache/ # exclude all files in the .pytest_cache directory 78 | | .*_pb2.py # exclude autogenerated Protocol Buffer files anywhere in the project 79 | ) 80 | ''' 81 | 82 | [tool.isort] 83 | profile = "black" 84 | skip = [".gitignore", ".dockerignore"] 85 | skip_glob = [".git/*", ".hatch/*", ".pytest_cache/*"] -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import pathlib 2 | 3 | from setuptools import find_packages, setup 4 | 5 | HERE = pathlib.Path(__file__).parent 6 | 7 | 8 | def get_version(): 9 | versionpath = pathlib.Path(HERE) / "obsws_python" / "version.py" 10 | with open(versionpath) as f: 11 | for line in f: 12 | if line.startswith("version"): 13 | versionstring = line.split('"')[1] 14 | return versionstring 15 | 16 | 17 | VERSION = get_version() 18 | PACKAGE_NAME = "obsws-python" 19 | AUTHOR = "Adem Atikturk" 20 | AUTHOR_EMAIL = "aatikturk@gmail.com" 21 | URL = "https://github.com/aatikturk/obsws-python" 22 | LICENSE = "GNU General Public License v3.0" 23 | DESCRIPTION = "A Python SDK for OBS Studio WebSocket v5.0" 24 | 25 | 26 | LONG_DESCRIPTION = (HERE / "README.md").read_text() 27 | LONG_DESC_TYPE = "text/markdown" 28 | 29 | # Dependencies for the package 30 | INSTALL_REQUIRES = ["websocket-client", "tomli >= 2.0.1;python_version < '3.11'"] 31 | 32 | # Development dependencies 33 | EXTRAS_REQUIRE = { 34 | "dev": [ 35 | "pytest", 36 | "pytest-randomly", 37 | "black", 38 | "isort", 39 | ] 40 | } 41 | 42 | # Python version requirement 43 | PYTHON_REQUIRES = ">=3.9" 44 | 45 | setup( 46 | name=PACKAGE_NAME, 47 | version=VERSION, 48 | description=DESCRIPTION, 49 | long_description=LONG_DESCRIPTION, 50 | long_description_content_type=LONG_DESC_TYPE, 51 | author=AUTHOR, 52 | license=LICENSE, 53 | author_email=AUTHOR_EMAIL, 54 | url=URL, 55 | install_requires=INSTALL_REQUIRES, 56 | extras_require=EXTRAS_REQUIRE, 57 | python_requires=PYTHON_REQUIRES, 58 | packages=find_packages(), 59 | ) 60 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | import obsws_python as obs 2 | 3 | req_cl = obs.ReqClient() 4 | 5 | 6 | def setup_module(): 7 | req_cl.create_scene("START_TEST") 8 | req_cl.create_scene("BRB_TEST") 9 | req_cl.create_scene("END_TEST") 10 | 11 | 12 | def teardown_module(): 13 | req_cl.remove_scene("START_TEST") 14 | req_cl.remove_scene("BRB_TEST") 15 | req_cl.remove_scene("END_TEST") 16 | resp = req_cl.get_studio_mode_enabled() 17 | if resp.studio_mode_enabled: 18 | req_cl.set_studio_mode_enabled(False) 19 | req_cl.base_client.ws.close() 20 | -------------------------------------------------------------------------------- /tests/test_attrs.py: -------------------------------------------------------------------------------- 1 | from tests import req_cl 2 | 3 | 4 | class TestAttrs: 5 | __test__ = True 6 | 7 | def test_get_version_attrs(self): 8 | resp = req_cl.get_version() 9 | assert resp.attrs() == [ 10 | "available_requests", 11 | "obs_version", 12 | "obs_web_socket_version", 13 | "platform", 14 | "platform_description", 15 | "rpc_version", 16 | "supported_image_formats", 17 | ] 18 | 19 | def test_get_current_program_scene_attrs(self): 20 | resp = req_cl.get_current_program_scene() 21 | assert resp.attrs() == [ 22 | "current_program_scene_name", 23 | "current_program_scene_uuid", 24 | "scene_name", 25 | "scene_uuid", 26 | ] 27 | 28 | def test_get_transition_kind_list_attrs(self): 29 | resp = req_cl.get_transition_kind_list() 30 | assert resp.attrs() == ["transition_kinds"] 31 | -------------------------------------------------------------------------------- /tests/test_callback.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from obsws_python.callback import Callback 4 | 5 | 6 | class TestCallbacks: 7 | __test__ = True 8 | 9 | @classmethod 10 | def setup_class(cls): 11 | cls.callback = Callback() 12 | 13 | @pytest.fixture(autouse=True) 14 | def wraps_tests(self): 15 | yield 16 | self.callback.clear() 17 | 18 | def test_register_callback(self): 19 | def on_callback_method(): 20 | pass 21 | 22 | self.callback.register(on_callback_method) 23 | assert self.callback.get() == ["CallbackMethod"] 24 | 25 | def test_register_callbacks(self): 26 | def on_callback_method_one(): 27 | pass 28 | 29 | def on_callback_method_two(): 30 | pass 31 | 32 | self.callback.register((on_callback_method_one, on_callback_method_two)) 33 | assert self.callback.get() == ["CallbackMethodOne", "CallbackMethodTwo"] 34 | 35 | def test_deregister_callback(self): 36 | def on_callback_method_one(): 37 | pass 38 | 39 | def on_callback_method_two(): 40 | pass 41 | 42 | self.callback.register((on_callback_method_one, on_callback_method_two)) 43 | self.callback.deregister(on_callback_method_one) 44 | assert self.callback.get() == ["CallbackMethodTwo"] 45 | 46 | def test_deregister_callbacks(self): 47 | def on_callback_method_one(): 48 | pass 49 | 50 | def on_callback_method_two(): 51 | pass 52 | 53 | def on_callback_method_three(): 54 | pass 55 | 56 | self.callback.register( 57 | (on_callback_method_one, on_callback_method_two, on_callback_method_three) 58 | ) 59 | self.callback.deregister((on_callback_method_two, on_callback_method_three)) 60 | assert self.callback.get() == ["CallbackMethodOne"] 61 | -------------------------------------------------------------------------------- /tests/test_error.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | import obsws_python as obsws 4 | from tests import req_cl 5 | 6 | 7 | class TestErrors: 8 | __test__ = True 9 | 10 | def test_it_raises_an_obssdk_error_on_incorrect_password(self): 11 | bad_conn = {"host": "localhost", "port": 4455, "password": "incorrectpassword"} 12 | with pytest.raises( 13 | obsws.error.OBSSDKError, 14 | match="failed to identify client with the server, please check connection settings", 15 | ): 16 | obsws.ReqClient(**bad_conn) 17 | 18 | def test_it_raises_an_obssdk_error_if_auth_enabled_but_no_password_provided(self): 19 | bad_conn = {"host": "localhost", "port": 4455, "password": ""} 20 | with pytest.raises( 21 | obsws.error.OBSSDKError, 22 | match="authentication enabled but no password provided", 23 | ): 24 | obsws.ReqClient(**bad_conn) 25 | 26 | def test_it_raises_a_request_error_on_invalid_request(self): 27 | with pytest.raises( 28 | obsws.error.OBSSDKRequestError, 29 | match="Request SetCurrentProgramScene returned code 600. With message: No source was found by the name of `invalid`.", 30 | ) as exc_info: 31 | req_cl.set_current_program_scene("invalid") 32 | 33 | e = exc_info.value 34 | assert e.req_name == "SetCurrentProgramScene" 35 | assert e.code == 600 36 | -------------------------------------------------------------------------------- /tests/test_request.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from tests import req_cl 4 | 5 | 6 | class TestRequests: 7 | __test__ = True 8 | 9 | def test_get_version(self): 10 | resp = req_cl.get_version() 11 | assert hasattr(resp, "obs_version") 12 | assert hasattr(resp, "obs_web_socket_version") 13 | 14 | def test_get_hot_key_list(self): 15 | resp = req_cl.get_hot_key_list() 16 | assert resp.hotkeys 17 | assert any(x.startswith("OBSBasic.") for x in resp.hotkeys) 18 | 19 | @pytest.mark.parametrize( 20 | "name,data", 21 | [ 22 | ("val1", 3), 23 | ("val2", "hello"), 24 | ], 25 | ) 26 | def test_persistent_data(self, name, data): 27 | req_cl.set_persistent_data("OBS_WEBSOCKET_DATA_REALM_PROFILE", name, data) 28 | resp = req_cl.get_persistent_data("OBS_WEBSOCKET_DATA_REALM_PROFILE", name) 29 | assert resp.slot_value == data 30 | 31 | @pytest.mark.skip(reason="possible bug in obs-websocket, needs checking") 32 | def test_profile_list(self): 33 | req_cl.create_profile("test") 34 | resp = req_cl.get_profile_list() 35 | assert "test" in resp.profiles 36 | req_cl.remove_profile("test") 37 | resp = req_cl.get_profile_list() 38 | assert "test" not in resp.profiles 39 | 40 | def test_stream_service_settings(self): 41 | settings = { 42 | "server": "rtmp://addressofrtmpserver", 43 | "key": "live_myvery_secretkey", 44 | } 45 | req_cl.set_stream_service_settings( 46 | "rtmp_common", 47 | settings, 48 | ) 49 | resp = req_cl.get_stream_service_settings() 50 | assert resp.stream_service_type == "rtmp_common" 51 | assert resp.stream_service_settings == { 52 | "server": "rtmp://addressofrtmpserver", 53 | "key": "live_myvery_secretkey", 54 | } 55 | 56 | @pytest.mark.parametrize( 57 | "scene", 58 | [ 59 | ("START_TEST"), 60 | ("BRB_TEST"), 61 | ("END_TEST"), 62 | ], 63 | ) 64 | def test_current_program_scene(self, scene): 65 | req_cl.set_current_program_scene(scene) 66 | resp = req_cl.get_current_program_scene() 67 | assert resp.current_program_scene_name == scene 68 | 69 | def test_input_list(self): 70 | req_cl.create_input( 71 | "START_TEST", "test", "color_source_v3", {"color": 4294945535}, True 72 | ) 73 | resp = req_cl.get_input_list() 74 | for input_item in resp.inputs: 75 | if input_item["inputName"] == "test": 76 | assert input_item["inputKind"] == "color_source_v3" 77 | assert input_item["unversionedInputKind"] == "color_source" 78 | break 79 | else: 80 | # This else block is executed if the for loop completes without finding the input_item with inputName "test" 81 | raise AssertionError("Input with inputName 'test' not found") 82 | 83 | resp = req_cl.get_input_settings("test") 84 | assert resp.input_kind == "color_source_v3" 85 | assert resp.input_settings == {"color": 4294945535} 86 | req_cl.remove_input("test") 87 | 88 | def test_source_filter(self): 89 | req_cl.create_source_filter("START_TEST", "test", "color_key_filter_v2") 90 | resp = req_cl.get_source_filter_list("START_TEST") 91 | assert resp.filters == [ 92 | { 93 | "filterEnabled": True, 94 | "filterIndex": 0, 95 | "filterKind": "color_key_filter_v2", 96 | "filterName": "test", 97 | "filterSettings": {}, 98 | } 99 | ] 100 | req_cl.remove_source_filter("START_TEST", "test") 101 | 102 | @pytest.mark.parametrize( 103 | "state", 104 | [ 105 | (False), 106 | (True), 107 | ], 108 | ) 109 | def test_studio_mode_enabled(self, state): 110 | req_cl.set_studio_mode_enabled(state) 111 | resp = req_cl.get_studio_mode_enabled() 112 | assert resp.studio_mode_enabled == state 113 | --------------------------------------------------------------------------------