class LiveChatStream: def __init__(self, video_id: str) -> None: self._livechat = LiveChat(video_id) def __enter__(self) -> LiveChatStream: return self def __exit__(self, *args) -> None: self.terminate() def terminate(self) -> None: self._livechat.terminate() def __call__(self) -> Iterator[Message]: while self._livechat.is_alive(): for item in self.get(): yield item def get(self) -> List[Message]: chatdata = self._livechat.get() chatlist = chatdata.items # type: List[BaseRenderer] if chatlist: chatdata.tick() messages = [Message.from_renderer(x) for x in chatlist] return messages
def main(): yt_url = get_stream_url() livechat = LiveChat(yt_url) hour_start = 19 min_start = 30 time_start = None time_chat = None count = 0 limit = 100 while livechat.is_alive(): chatdata = livechat.get() for c in chatdata.items: if not bool(time_start): len_time = len(" 19:30:00") time_start = dt.datetime.strptime(c.datetime[:-len_time], "%Y-%m-%d") time_start = time_start.replace(hour=hour_start, minute=min_start) time_chat = dt.datetime.strptime(c.datetime, "%Y-%m-%d %H:%M:%S") if time_chat >= time_start: print("{} [{}]- {}".format(c.datetime, c.author.name, c.message)) count += 1 print("count = {}".format(count)) chatdata.tick() if count > limit: break if count > limit: break
def pipeYoutubeChat(activeYoutubeLink): livechat = LiveChat(activeYoutubeLink) while livechat.is_alive(): try: chatdata = livechat.get() for c in chatdata.items: print(f"{c.datetime} [{c.author.name}]- {c.message}") requests.post(DISCORD_CHAT_WEBHOOK, json={ "content": c.message, "username": f"YT: {c.author.name}" }) chatdata.tick() except KeyboardInterrupt: livechat.terminate() break print("Terminated chat bridge.")
def workload(vid_id): data = [] vid_path = ROOT.joinpath(vid_id + ".json") if vid_path.exists(): logger.critical("File already exists for stream {}", vid_id) return logger.debug("task {} started", vid_id) def callback(chat_data: Chatdata): logger.debug("Processing Data") for chat in chat_data.items: chat: Chat json_data: dict = json.loads(chat.json()) logger.debug(f"S:[{json_data['author']['name']}][{json_data['timestamp']}][{json_data['message']}]") data.append(json_data) try: # live_chat = LiveChatAsync(vid_id, callback=callback) live_chat = LiveChat(vid_id, callback=callback, force_replay=True) except Exception: raise else: while live_chat.is_alive(): time.sleep(3) try: live_chat.raise_for_status() except ChatDataFinished: logger.info("Chat data finished.") except Exception: raise if data: new_dict = {idx: chat_json for idx, chat_json in enumerate(data)} vid_path.write_text(json.dumps(new_dict, indent=2), encoding="utf8") logger.info("Written {} chats for {}", len(data), vid_id) else: logger.warning("No data to write")
class collector(threading.Thread): def __init__(self, text, textor): super(collector, self).__init__() self.livechat = False self.program_running = True self.running = False self.text = textor def setlink(self, link): self.running = False if self.livechat: self.livechat.terminate() try: self.livechat = LiveChat(link) self.running = True self.text.settext('collecting\n > ' + link + '\n') return True except: print("link error") self.running = False return False def exit(self): if self.livechat: self.livechat.terminate() self.running = False self.program_running = False def run(self): while self.program_running: while self.running and self.livechat.is_alive(): try: self.chatdata = self.livechat.get() for c in self.chatdata.items: if not self.running: break d = condition(c.message, c.author) if d: maintranslatoradd(c.author.name) self.text.settext(d + '\n') self.chatdata.tick() except KeyboardInterrupt: self.livechat.terminate() break time.sleep(0.1)
class collector(thr): def __init__(self): super(collector,self).__init__() self.livechat=False self.program_running=True self.running=False def setlink(self,link): if self.livechat: self.livechat.terminate() self.livechat = LiveChat(link) self.running=True def exit(self): self.livechat.terminate() self.running=False self.program_running=False def run(self): while self.program_running: while self.running and self.livechat.is_alive(): try: self.chatdata = self.livechat.get() for c in self.chatdata.items: if not self.running:break d=condition(c.message,c.author) if d: maintranslatoradd(c.author.name) print(f"[ >{c.author.name} ({maintranslator[c.author.name]})]") print(d,end="\n\n") self.chatdata.tick() except KeyboardInterrupt: self.livechat.terminate() break except Exception as e: print(e) break time.sleep(0.1)
class collector(threading.Thread): def __init__(self): super(collector,self).__init__() self.livechat=False self.program_running=True self.running=False # self.t=time.time() def setlink(self,link): if self.livechat: self.livechat.terminate() self.livechat = LiveChat(link) self.running=True def exit(self): self.livechat.terminate() self.running=False self.program_running=False def run(self): while self.program_running: while self.running: while self.livechat.is_alive(): if not self.program_running: break try: try:self.chatdata = self.livechat.get() except:break for c in self.chatdata.items: d=condition(c.message,c.author) if d: maintranslatoradd(c.author.name) print(d) text.insert(1.0,d) self.chatdata.tick() except KeyboardInterrupt: self.livechat.terminate() time.sleep(0.1)
livechat = LiveChat(video_id="hMvmbGy3qq8") scope = [ 'https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive' ] creds = ServiceAccountCredentials.from_json_keyfile_name( 'Spreadsheetapi-03009ddbdc6b.json', scope) client = gspread.authorize(creds) sheet = client.open("Rekap Soal Webinar").sheet1 data = sheet.get_all_records() print(data) print(livechat.is_alive()) count = len(data) while livechat.is_alive(): chatdata = livechat.get() # print("live") for c in chatdata.items: print(f"{c.datetime} [{c.author.name}]- {c.message}") value = c.message if value.count("#") >= 3: values = value.split("#") sheet.insert_row(values, count + 2) print("berhasil ditambah") print("count " + str(count)) count += 1
# client = MongoClient() client = MongoClient( "mongodb+srv://new_user:[email protected]/<dbname>?retryWrites=true&w=majority" ) db = client["mydb"] comments = db["customer"] # # livechat = LiveChat("https://www.youtube.com/watch?v=H_od47aWu-s") livechat = LiveChat(sys.argv[1]) # while livechat.is_alive(): try: chatdata = livechat.get() for c in chatdata.items: print(f" [{c.author.name}]- {c.message}") username = c.author.name comment = c.message comm = {"name": username, "comment": comment} comments.insert_one(comm) chatdata.tick() except KeyboardInterrupt: livechat.terminate() break
layout = [ [sg.Text('Enter Stream URL (youtube or twitch)')], [sg.InputText(key='streamid')], [sg.Text('_'*100)], [sg.Checkbox('Donation Message (100+ bits on twitch)', key='donmsg'), sg.Checkbox('Chat Message',key='chatmsg')], [sg.Submit()] ] window = sg.Window('Livestream Chat Narrator', layout, resizable=True,) while True: event, values = window.read() chat = LiveChat(video_id=values['streamid'][values['streamid'].find('=')+1:]) if 'youtube.com' in values['streamid'].lower(): #youtube textbox if values['donmsg']==True: print("youtube stream selected - donation messages selected - program activated") window.Refresh() while chat.is_alive(): try: data = chat.get() items = data.items for c in items: if c.amountValue > float(0.0): print(f"{c.datetime} [{c.author.name}] - {c.message} - {c.amountString}") engine = pyttsx3.init() engine.setProperty('rate', 135) engine.say(c.author.name+' donated '+c.amountValue+' and says '+c.message) engine.runAndWait() print('finished playing audio message') except KeyboardInterrupt: chat.terminate() break if values['chatmsg']==True: