-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.py
213 lines (168 loc) · 6.16 KB
/
index.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import io
import os
import json
import time
import flask
import pprint
import string
import socket
import threading
from pathlib import Path
from config import Config
from flask import render_template
import voice
from sse import Publisher
from makedirs import MakeDirs
publisher = Publisher()
_threadFacebook = None
_threadTwitch = None
_threadYoutube = None
_threadDouyu = None
_now_timestamp = int(time.time())
_now_array = time.localtime(_now_timestamp)
_now_day_string = time.strftime("%Y-%m-%d", _now_array)
# ==============================
# Flask Route
# ==============================
app = flask.Flask(__name__)
@app.route('/')
def index():
MakeDirs()
chart()
return render_template(f"{Config.CHAT_VIEW}.html")
@app.route('/notify')
def notify():
return flask.Response(publisher.subscribe(), content_type='text/event-stream')
# ==============================
# 直播平台監聽
# ==============================
def chart():
if Config.FACEBOOK_ACTIVE:
global _threadFacebook
if _threadFacebook is None:
print("[DEBUG] 啟動 Facebook 直播監聽 ...")
_threadFacebook = threading.Thread(target=facebookLive)
_threadFacebook.start()
pass
else:
print("[DEBUG] Facebook 直播監聽正在運作當中。")
pass
if Config.TWITCH_ACTIVE:
global _threadTwitch
if _threadTwitch is None:
print("[DEBUG] 啟動 Twitch 直播監聽 ...")
_threadTwitch = threading.Thread(target=twitchLive)
_threadTwitch.start()
pass
else:
print("[DEBUG] Twitch 直播監聽正在運作當中。")
pass
if Config.YOUTUBE_ACTIVE:
global _threadYoutube
if _threadYoutube is None:
print("[DEBUG] 啟動 YouTube 直播監聽 ...")
_threadYoutube = threading.Thread(target=youtubeLiveChat)
_threadYoutube.start()
pass
else:
print("[DEBUG] YouTube 直播監聽正在運作當中。")
pass
if Config.DOUYU_ACTIVE:
global _threadDouyu
if _threadDouyu is None:
print("[DEBUG] 啟動 DouYu 直播監聽 ...")
_threadDouyu = threading.Thread(target=douyuLive)
_threadDouyu.start()
pass
else:
print("[DEBUG] DouYu 直播監聽正在運作當中。")
pass
def facebookLive():
""""輸出 Facebook 的聊天內容。"""
import sseclient
url = "https://streaming-graph.facebook.com/" + Config.FACEBOOK_LIVE_VIDEO_ID + "/live_comments?access_token=" + Config.FACEBOOK_ACCESS_TOKEN + "&comment_rate=one_per_two_seconds&fields=from{name,picture,id},message"
response = with_urllib3(url)
client = sseclient.SSEClient(response)
for event in client.events():
data = json.loads(event.data)
ssePublish('facebook', data['from']['name'], data['message'], data['from']['picture']['data']['url'])
if Config.SPEECH_ACTIVE:
voice.voice(data['message'])
def twitchLive():
import twitch
helix = twitch.Helix(client_id=Config.TWITCH_CLIENT_ID,
use_cache=True,
bearer_token=Config.TWITCH_BEARER_TOKEN)
twitch.Chat(channel=Config.TWITCH_CHANNEL,
nickname=Config.TWITCH_NICKNAME,
oauth=Config.TWITCH_OAUTH_TOKEN).subscribe(lambda message: twitchChat(message, helix))
# oauth=Config.TWITCH_OAUTH_TOKEN).subscribe(lambda message: twitchChat(message))
# def twitchChat(data):
def twitchChat(data, helix):
""""輸出 Twitch 的聊天內容。"""
# ssePublish('twitch', data.sender, data.text)
author = helix.user(data.sender)
ssePublish('twitch', author.display_name, data.text, author.profile_image_url)
if Config.SPEECH_ACTIVE:
voice.voice(data.text)
def youtubeLiveChat():
from pytchat import CompatibleProcessor, LiveChat as youtubeClient
youtubeChat = youtubeClient(
Config.YOUTUBE_LIVE_VIDEO_ID,
processor=CompatibleProcessor())
while youtubeChat.is_alive():
try:
data = youtubeChat.get()
polling = data['pollingIntervalMillis']/1000
for chat in data['items']:
if chat.get('snippet'):
ssePublish('youtube',
chat['authorDetails']['displayName'],
chat['snippet']['displayMessage'])
if Config.SPEECH_ACTIVE:
voice.voice(chat['snippet']['displayMessage'])
time.sleep(polling/len(data['items']))
except KeyboardInterrupt:
youtubeChat.terminate()
except Exception as e:
print("youtube failed. Exception: %s" % e)
def douyuLive():
from pydouyu.client import Client as douyuClient
douyu = douyuClient(room_id=Config.DOUYU_ROOM_ID,
barrage_host=Config.DOUYU_BARRAGE_HOST)
douyu.add_handler('chatmsg', douyuChat)
douyu.start()
def douyuChat(data):
try:
ssePublish('douyu', data['nn'], data['txt'])
if Config.SPEECH_ACTIVE:
voice.voice(data['txt'])
except Exception as e:
print("douyuLiveMessage failed. Exception: %s" % e)
# ==============================
# Custom function
# ==============================
def ssePublish(type, name, message, picture = None):
print(f"[DEBUG] {type} - {name}: {message}")
publisher.publish(
json.dumps({
"channel": type,
"author": name,
"message": message,
"picture": picture,
"time": time.strftime("%H:%M:%S")
}))
def with_urllib3(url):
"""Get a streaming response for the given event feed using urllib3."""
import urllib3
http = urllib3.PoolManager()
return http.request('GET', url, preload_content=False)
def with_requests(url):
"""Get a streaming response for the given event feed using requests."""
import requests
return requests.get(url, stream=True)
# ==============================
# __name__
# ==============================
if __name__ == "__main__":
app.run(debug=True, threaded=True)