简体   繁体   中英

Need some advice with Twitch.tv code that uses the JSON data available to select a random streamer

I've been working on a program that will open streams of streamers, when the user enters the streamers name. Here is my code:

import subprocess,urllib.request,json

wcsChannels=["wcs_europe","wcs_europe2","wcs_america","wcs_america2","wcs_europe_de"]

def openStream(s,q="high"):
    subprocess.Popen("livestreamer.exe twitch.tv/"+s+" "+q,shell=True).wait()
    print(s,"is not online.")

def QS(s):
    if s=="wcs":
        wcs("high")
    if s=="d":
        openStream("dragon")
    if s=="rotti":
        openStream("rotterdam08")

def wcs(q):
    for i in range(0,5):
        openStream(wcsChannels[i],q) # will try and open all wcs streams

menu=int(input("""Twitch Channeler
1 - Open Stream
2 - Random Stream
: """))
if menu==1:
    qs=input("QS: ") # qs=quick stream
    if qs!="":
        QS(qs)
    streamer=input("Streamer (full name): ")
    quality=input("Quality: ").lower()
    subprocess.Popen("livestreamer.exe twitch.tv/"+streamer+" "+quality,shell=True).wait()

elif menu==2:
    streamers=urllib.request.urlopen("https://api.twitch.tv/kraken/streams/?game=StarCraft%20II:%20Heart%20of%20the%20Swarm")

My problem is that, towards the end, I'm not sure how to work with the json data given from the twitch url at: https://api.twitch.tv/kraken/streams/?game=StarCraft%20II:%20Heart%20of%20the%20Swarm . I need it to add all the users at streams/channels/display_name, put it all in one list and pick a random name from the list.

I've also been researching the JSON module in addition to the pprint one, but can only either find outdated 2.x modules or code that I'm not sure how to adapt to my situation.

All help is appreciated.

The json module in standard library is perfectly fine for processing the json data from the url that you have given. You can learn more about json module from the offical documentation here .

This is an example how to do what you asked for.

import urllib, json, random

streamers = urllib.urlopen("https://api.twitch.tv/kraken/streams/?game=StarCraft%20II:%20Heart%20of%20the%20Swarm")
streamers_data = json.loads(streamers.readlines()[0])
display_names = [stream['channel']['display_name'] for stream in streamers_data['streams']]
print random.choice(display_names)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM