Skip to main content
https://readthedocs.org/projects/python-twitch-stream/badge/ https://travis-ci.org/317070/python-twitch-stream.svg https://coveralls.io/repos/317070/python-twitch-stream/badge.svg https://img.shields.io/badge/license-MIT-green.svg

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.

pip install python-twitch-stream

Make sure to also install a recent ffmpeg version:

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:

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.

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.

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, and check the Tutorial for in-depth explanations of the same. More examples are maintained in the examples directory.

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

Release files for python-twitch-stream 1.0.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for python-twitch-stream 1.0.2
File Size Uploaded
python-twitch-stream-1.0.2.tar.gz 22.2 kB Details

Built distributions (wheels)

Table of built distributions (wheels) for python-twitch-stream 1.0.2
File Interpreter ABI Platform
python_twitch_stream-1.0.2-py2.py3-none-any.whl Python 2, Python 3 none any Details
python_twitch_stream-1.0.2-py2-none-any.whl Python 2 none any Details

Total release size: 59.8 kB

Release files / python-twitch-stream-1.0.2.tar.gz

Download URL python-twitch-stream-1.0.2.tar.gz
Size 22.2 kB
Tags Source
SHA-256 checksum
How to use checksums
a38d950d1f4904d8316f2c7be375c0f08175a14059cd05c9134a07c8d2968aec
BLAKE2b-256 checksum
How to use checksums
7c2fdf6319b8cf1c31e1e17ba5167bf02c00ddf04f0e5e8de936ef8132bb0595
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Release files / python_twitch_stream-1.0.2-py2.py3-none-any.whl

Download URL python_twitch_stream-1.0.2-py2.py3-none-any.whl
Size 18.8 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
03b2a43f28e0730d1708d5d5ac99fa69a763b887629f84e86499d1307260a0bb
BLAKE2b-256 checksum
How to use checksums
3c1cfb821e36fa40316442f59c152d1632a46fceedd04056707c8950159d0671
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Release files / python_twitch_stream-1.0.2-py2-none-any.whl

Download URL python_twitch_stream-1.0.2-py2-none-any.whl
Size 18.8 kB
Tags Python 2
SHA-256 checksum
How to use checksums
b33c90278bef71d17c1a85205067387c7c032c867cfffa8568c2062e082d3910
BLAKE2b-256 checksum
How to use checksums
b1020b8af16deadf662dcd3c28a63b4fcb417729a0f858cbc9bcbc84ae6922fc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Release history Release notifications | RSS feed

This release

1.0.2 This release

3 release files

1.0.1

2 release files

1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page