twitch-stream.py


Nametwitch-stream.py JSON
Version 1.1.2 PyPI version JSON
download
home_pagehttps://github.com/317070/python-twitch-stream
SummaryAn interface to the Twitch website, to interact with their video and chat
upload_time2023-04-20 06:19:26
maintainer
docs_urlNone
authorJonas Degrave
requires_python
licenseMIT
keywords twitch stream video chat
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI
coveralls test coverage
            .. image:: https://readthedocs.org/projects/python-twitch-stream/badge/
    :target: http://python-twitch-stream.readthedocs.org/en/latest/

.. image:: https://travis-ci.org/317070/python-twitch-stream.svg
    :target: https://travis-ci.org/317070/python-twitch-stream

.. image:: https://coveralls.io/repos/317070/python-twitch-stream/badge.svg
    :target: https://coveralls.io/github/317070/python-twitch-stream

.. image:: https://img.shields.io/badge/license-MIT-green.svg
    :target: https://github.com/Lasagne/Lasagne/blob/master/LICENSE

Python-Twitch-Stream
====================

Python-twitch-stream is a simple lightweight library, which you can use to
send your python video to twitch and react with the chat in real time.
Its main features are:

* Supports sending of audio and video in a thread safe way to your twitch
  channel.
* Allows to interact with the chat of your channel by sending chat messages
  and reading what other users post.


Installation
------------

In short, you can install a known compatible version of ffmpeg and
the latest stable version over pip.

.. code-block:: bash

  pip install python-twitch-stream

Make sure to also install a recent ffmpeg version:

.. code-block:: bash

  sudo add-apt-repository ppa:mc3man/trusty-media
  sudo apt-get update && sudo apt-get install ffmpeg

The ffmpeg library needs to be very recent (written in october 2015).
There are plenty of bugs when
running a stream using older versions of ffmpeg or avconv, including but
not limited to 6GB of memory use, problems with the audio and
synchronization of the audio and the video.

Or alternatively, install the latest
python-twitch-stream development version via:

.. code-block:: bash

  pip install git+https://github.com/317070/python-twitch-stream


Documentation
-------------

Documentation is available online: http://python-twitch-stream.readthedocs.org/

For support, please use the github issues on `the repository
<https://github.com/317070/python-twitch-stream/issues>`_.


Example
-------

This is a small example which creates a twitch stream which
changes the color of the video according to the colors provided in
the chat.

.. code-block:: python

    from __future__ import print_function
    from twitchstream.outputvideo import TwitchBufferedOutputStream
    from twitchstream.chat import TwitchChatStream
    import argparse
    import time
    import numpy as np

    if __name__ == "__main__":
        parser = argparse.ArgumentParser(description=__doc__)
        required = parser.add_argument_group('required arguments')
        required.add_argument('-u', '--username',
                              help='twitch username',
                              required=True)
        required.add_argument('-o', '--oauth',
                              help='twitch oauth '
                                   '(visit https://twitchapps.com/tmi/ '
                                   'to create one for your account)',
                              required=True)
        required.add_argument('-s', '--streamkey',
                              help='twitch streamkey',
                              required=True)
        args = parser.parse_args()

        # load two streams:
        # * one stream to send the video
        # * one stream to interact with the chat
        with TwitchBufferedOutputStream(
                twitch_stream_key=args.streamkey,
                width=640,
                height=480,
                fps=30.,
                enable_audio=True,
                verbose=False) as videostream, \
            TwitchChatStream(
                username=args.username.lower(),  # Must provide a lowercase username.
                oauth=args.oauth,
                verbose=False) as chatstream:

            # Send a chat message to let everybody know you've arrived
            chatstream.send_chat_message("Taking requests!")

            frame = np.zeros((480, 640, 3))
            frequency = 100
            last_phase = 0

            # The main loop to create videos
            while True:

                # Every loop, call to receive messages.
                # This is important, when it is not called,
                # Twitch will automatically log you out.
                # This call is non-blocking.
                received = chatstream.twitch_receive_messages()

                # process all the messages
                if received:
                    for chat_message in received:
                        print("Got a message '%s' from %s" % (
                            chat_message['message'],
                            chat_message['username']
                        ))
                        if chat_message['message'] == "red":
                            frame[:, :, :] = np.array(
                                [1, 0, 0])[None, None, :]
                        elif chat_message['message'] == "green":
                            frame[:, :, :] = np.array(
                                [0, 1, 0])[None, None, :]
                        elif chat_message['message'] == "blue":
                            frame[:, :, :] = np.array(
                                [0, 0, 1])[None, None, :]
                        elif chat_message['message'].isdigit():
                            frequency = int(chat_message['message'])

                # If there are not enough video frames left,
                # add some more.
                if videostream.get_video_frame_buffer_state() < 30:
                    videostream.send_video_frame(frame)

                # If there are not enough audio fragments left,
                # add some more, but take care to stay in sync with
                # the video! Audio and video buffer separately,
                # so they will go out of sync if the number of video
                # frames does not match the number of audio samples!
                elif videostream.get_audio_buffer_state() < 30:
                    x = np.linspace(last_phase,
                                    last_phase +
                                    frequency*2*np.pi/videostream.fps,
                                    int(44100 / videostream.fps) + 1)
                    last_phase = x[-1]
                    audio = np.sin(x[:-1])
                    videostream.send_audio(audio, audio)

                # If nothing is happening, it is okay to sleep for a while
                # and take some pressure of the CPU. But not too long, if
                # the buffers run dry, audio and video will go out of sync.
                else:
                    time.sleep(.001)


For a fully-functional example, see `examples/color.py <examples/color.py>`_,
and check the `Tutorial
<http://317070.github.io/python/>`_ for in-depth
explanations of the same. More examples are maintained in the `examples directory
<examples>`_.


Development
-----------

Python-twitch-stream is a work in progress, but is stable. Feel free to ask
for features or add pull-requests with updates on the code.


Changelog
---------

1.0 (2015-10-30)
~~~~~~~~~~~~~~~~

First release.
Features:

* Sending Twitch streams (video and audio)
* Reading and sending Twitch chats.

* core contributors, in alphabetical order:

  * Jonas Degrave (@317070)

* Special thanks to

  * Frederik Tejner Witte for his `great tutorial <http://www.wituz.com/tutorial-make-your-own-twitch-plays-stream.html>`_!



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/317070/python-twitch-stream",
    "name": "twitch-stream.py",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "twitch,stream,video,chat",
    "author": "Jonas Degrave",
    "author_email": "erstaateenknolraapinmijntuin+pythontwitch@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/cd/bf/b6b56f8e572899b7abcb097edc63d67d11187d01f5cb3097b4cf49abbd03/twitch-stream.py-1.1.2.tar.gz",
    "platform": null,
    "description": ".. image:: https://readthedocs.org/projects/python-twitch-stream/badge/\n    :target: http://python-twitch-stream.readthedocs.org/en/latest/\n\n.. image:: https://travis-ci.org/317070/python-twitch-stream.svg\n    :target: https://travis-ci.org/317070/python-twitch-stream\n\n.. image:: https://coveralls.io/repos/317070/python-twitch-stream/badge.svg\n    :target: https://coveralls.io/github/317070/python-twitch-stream\n\n.. image:: https://img.shields.io/badge/license-MIT-green.svg\n    :target: https://github.com/Lasagne/Lasagne/blob/master/LICENSE\n\nPython-Twitch-Stream\n====================\n\nPython-twitch-stream is a simple lightweight library, which you can use to\nsend your python video to twitch and react with the chat in real time.\nIts main features are:\n\n* Supports sending of audio and video in a thread safe way to your twitch\n  channel.\n* Allows to interact with the chat of your channel by sending chat messages\n  and reading what other users post.\n\n\nInstallation\n------------\n\nIn short, you can install a known compatible version of ffmpeg and\nthe latest stable version over pip.\n\n.. code-block:: bash\n\n  pip install python-twitch-stream\n\nMake sure to also install a recent ffmpeg version:\n\n.. code-block:: bash\n\n  sudo add-apt-repository ppa:mc3man/trusty-media\n  sudo apt-get update && sudo apt-get install ffmpeg\n\nThe ffmpeg library needs to be very recent (written in october 2015).\nThere are plenty of bugs when\nrunning a stream using older versions of ffmpeg or avconv, including but\nnot limited to 6GB of memory use, problems with the audio and\nsynchronization of the audio and the video.\n\nOr alternatively, install the latest\npython-twitch-stream development version via:\n\n.. code-block:: bash\n\n  pip install git+https://github.com/317070/python-twitch-stream\n\n\nDocumentation\n-------------\n\nDocumentation is available online: http://python-twitch-stream.readthedocs.org/\n\nFor support, please use the github issues on `the repository\n<https://github.com/317070/python-twitch-stream/issues>`_.\n\n\nExample\n-------\n\nThis is a small example which creates a twitch stream which\nchanges the color of the video according to the colors provided in\nthe chat.\n\n.. code-block:: python\n\n    from __future__ import print_function\n    from twitchstream.outputvideo import TwitchBufferedOutputStream\n    from twitchstream.chat import TwitchChatStream\n    import argparse\n    import time\n    import numpy as np\n\n    if __name__ == \"__main__\":\n        parser = argparse.ArgumentParser(description=__doc__)\n        required = parser.add_argument_group('required arguments')\n        required.add_argument('-u', '--username',\n                              help='twitch username',\n                              required=True)\n        required.add_argument('-o', '--oauth',\n                              help='twitch oauth '\n                                   '(visit https://twitchapps.com/tmi/ '\n                                   'to create one for your account)',\n                              required=True)\n        required.add_argument('-s', '--streamkey',\n                              help='twitch streamkey',\n                              required=True)\n        args = parser.parse_args()\n\n        # load two streams:\n        # * one stream to send the video\n        # * one stream to interact with the chat\n        with TwitchBufferedOutputStream(\n                twitch_stream_key=args.streamkey,\n                width=640,\n                height=480,\n                fps=30.,\n                enable_audio=True,\n                verbose=False) as videostream, \\\n            TwitchChatStream(\n                username=args.username.lower(),  # Must provide a lowercase username.\n                oauth=args.oauth,\n                verbose=False) as chatstream:\n\n            # Send a chat message to let everybody know you've arrived\n            chatstream.send_chat_message(\"Taking requests!\")\n\n            frame = np.zeros((480, 640, 3))\n            frequency = 100\n            last_phase = 0\n\n            # The main loop to create videos\n            while True:\n\n                # Every loop, call to receive messages.\n                # This is important, when it is not called,\n                # Twitch will automatically log you out.\n                # This call is non-blocking.\n                received = chatstream.twitch_receive_messages()\n\n                # process all the messages\n                if received:\n                    for chat_message in received:\n                        print(\"Got a message '%s' from %s\" % (\n                            chat_message['message'],\n                            chat_message['username']\n                        ))\n                        if chat_message['message'] == \"red\":\n                            frame[:, :, :] = np.array(\n                                [1, 0, 0])[None, None, :]\n                        elif chat_message['message'] == \"green\":\n                            frame[:, :, :] = np.array(\n                                [0, 1, 0])[None, None, :]\n                        elif chat_message['message'] == \"blue\":\n                            frame[:, :, :] = np.array(\n                                [0, 0, 1])[None, None, :]\n                        elif chat_message['message'].isdigit():\n                            frequency = int(chat_message['message'])\n\n                # If there are not enough video frames left,\n                # add some more.\n                if videostream.get_video_frame_buffer_state() < 30:\n                    videostream.send_video_frame(frame)\n\n                # If there are not enough audio fragments left,\n                # add some more, but take care to stay in sync with\n                # the video! Audio and video buffer separately,\n                # so they will go out of sync if the number of video\n                # frames does not match the number of audio samples!\n                elif videostream.get_audio_buffer_state() < 30:\n                    x = np.linspace(last_phase,\n                                    last_phase +\n                                    frequency*2*np.pi/videostream.fps,\n                                    int(44100 / videostream.fps) + 1)\n                    last_phase = x[-1]\n                    audio = np.sin(x[:-1])\n                    videostream.send_audio(audio, audio)\n\n                # If nothing is happening, it is okay to sleep for a while\n                # and take some pressure of the CPU. But not too long, if\n                # the buffers run dry, audio and video will go out of sync.\n                else:\n                    time.sleep(.001)\n\n\nFor a fully-functional example, see `examples/color.py <examples/color.py>`_,\nand check the `Tutorial\n<http://317070.github.io/python/>`_ for in-depth\nexplanations of the same. More examples are maintained in the `examples directory\n<examples>`_.\n\n\nDevelopment\n-----------\n\nPython-twitch-stream is a work in progress, but is stable. Feel free to ask\nfor features or add pull-requests with updates on the code.\n\n\nChangelog\n---------\n\n1.0 (2015-10-30)\n~~~~~~~~~~~~~~~~\n\nFirst release.\nFeatures:\n\n* Sending Twitch streams (video and audio)\n* Reading and sending Twitch chats.\n\n* core contributors, in alphabetical order:\n\n  * Jonas Degrave (@317070)\n\n* Special thanks to\n\n  * Frederik Tejner Witte for his `great tutorial <http://www.wituz.com/tutorial-make-your-own-twitch-plays-stream.html>`_!\n\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "An interface to the Twitch website, to interact with their video and chat",
    "version": "1.1.2",
    "split_keywords": [
        "twitch",
        "stream",
        "video",
        "chat"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "cdbfb6b56f8e572899b7abcb097edc63d67d11187d01f5cb3097b4cf49abbd03",
                "md5": "70d2f640d0aef247871276216d36152e",
                "sha256": "a3e89f18772d5e6ef67a57c27d4b6e84b7ffc6c2dc49c380b6a3a94d4ce31226"
            },
            "downloads": -1,
            "filename": "twitch-stream.py-1.1.2.tar.gz",
            "has_sig": false,
            "md5_digest": "70d2f640d0aef247871276216d36152e",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 48241,
            "upload_time": "2023-04-20T06:19:26",
            "upload_time_iso_8601": "2023-04-20T06:19:26.956581Z",
            "url": "https://files.pythonhosted.org/packages/cd/bf/b6b56f8e572899b7abcb097edc63d67d11187d01f5cb3097b4cf49abbd03/twitch-stream.py-1.1.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-04-20 06:19:26",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "317070",
    "github_project": "python-twitch-stream",
    "travis_ci": true,
    "coveralls": true,
    "github_actions": false,
    "requirements": [],
    "lcname": "twitch-stream.py"
}
        
Elapsed time: 0.06439s