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
class Pychat: def __init__(self, video, parser=YoutubeParser()): self.live_chat = LiveChat(video_id=video.id, processor=CompatibleProcessor()) self._parser = parser def terminate(self): self.live_chat.terminate() def get_messages(self): return self._parser(self.live_chat.get())
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 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")
def geturl(): global live_chat global mo # Get video URL and split off the video ID while True: print("Please enter the YouTube Live Stream URL, then press Enter: ") video_url = input() try: url = re.compile( r'^((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?$' ) mo = url.search(video_url) live_chat = LiveChat(mo.group(5)) break except: print("Invalid YouTube URL! Please try again!\n") continue
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 main(config, chat_config_path): try: chat_id = str(config["chat_id"]) pg_window = PygameWindow(window_size=config["window_size"], bg_color=config["background_color"]) except KeyError or TypeError: logger.error("Error invalid config.json format") sys.exit(-1) chat_player = ChatPlayer(pg_window, chat_config_path) def process_comment(data): for c in data.items: chat_player.process_comment([c.author.name, c.message]) data.tick() try: chat_getter = LiveChat(chat_id, callback=process_comment) except: logger.error("Error during LiveChat initialize") traceback.print_exc() pg_window.quit() return True @pg_window.main def loop(): if not chat_getter.is_alive() or get_quit_event(): chat_getter.terminate() pg_window.quit() sys.exit(0) chat_player.test(get_test_event()) while True: loop()
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)
import time from pytchat import LiveChat import pyttsx3 from twitchobserver import Observer 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()
def setlink(self,link): if self.livechat: self.livechat.terminate() self.livechat = LiveChat(link) self.running=True
def __init__(self, video, parser=YoutubeParser()): self.live_chat = LiveChat(video_id=video.id, processor=CompatibleProcessor()) self._parser = parser
def __init__(self, video_id: str) -> None: self._livechat = LiveChat(video_id)
from pytchat import LiveChat a=input('link:') livechat = LiveChat(a) def condition(s,n): if n.name=='Fah': return True #if there is a usual translator you can input there name here z=s.lower() if 'en]' in z or '[en' in z or u'【en' in z or u'(en' in z or 'talking about' in z: return True #some time they will translate as"[EN]:she is talking about..." if n.isVerified: return True #check if there is some channel comment?if its japanese you can use translate with in https://github.com/fah-OwO/realtime-auto-translate-using-clipboard/blob/master/autotranslate.py if s.count(':')==1: return True #some time it will be like "subaru:she is talking about" and I use count as 1 because there will be emoticon like :":_ナンバー1:" or ":_にこにこ:" return False #you can add case condition by your self print("start with > to show that those message match translate message condition") while livechat.is_alive(): try: chatdata = livechat.get() for c in chatdata.items: if condition(c.message,c.author): print(f" > {c.message}") chatdata.tick() except KeyboardInterrupt: livechat.terminate() break print("live chat end") input("press enter to exit")
chat_data.tick() except KeyboardInterrupt: live_chat.terminate() break if not live_chat.is_alive(): print("URL is not currently a live stream") print("Would you like to start on the recorded stream? (y/n)") while True: playback = input("> ") if playback.lower() == 'y' or playback.lower() == 'n': break else: print('Please enter (y) or (n)!') if playback == 'y': live_chat = LiveChat(mo.group(5), seektime=1) while live_chat: try: chat_data = live_chat.get() for c in chat_data.items: if c.author.name in myList: if alarm.exists(): playsound(alarm_filename) print("{} [{}] - {}".format(c.datetime, c.author.name, c.message)) chat_data.tick() except KeyboardInterrupt: live_chat.terminate() sys.exit() else: print("Program will now exit...")
from pytchat import LiveChat from pymongo import MongoClient import sys # 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:
from pytchat import LiveChat livechat = LiveChat(video_id="1gvpuY6ISoI") # It is also possible to specify a URL that includes the video ID: # livechat = LiveChat("https://www.youtube.com/watch?v=Zvp1pJpie4I") while livechat.is_alive(): try: chatdata = livechat.get() for c in chatdata.items: try: print(f"{c.message}") chatdata.tick() except: pass except KeyboardInterrupt: livechat.terminate() break
from pytchat import LiveChat import time import json import pprint import pathlib # chat_id = "LLw58K_VVwE" chat_id = input("Stream ID:") members = set() def callback(chat_data): for chat in chat_data.items: json_data: dict = json.loads(chat.json()) members.add(json_data["author"]["name"]) pprint.pprint(members) livechat = LiveChat(chat_id, callback=callback, direct_mode=True) while livechat.is_alive(): time.sleep(3) livechat.raise_for_status() if members: save_file = pathlib.Path(__file__).parent.joinpath(chat_id + ".json") save_file.write_text(json.dumps(members, indent=2), "utf8")
# import keyboard import gspread from oauth2client.service_account import ServiceAccountCredentials from pytchat import LiveChat 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("#")
video_id = 'am_AtPfV_Jk' v = pafy.new(video_id) title = v.title author = v.author published = v.published print(title) print(author) print(published) empty_frame = pd.DataFrame( columns=['제목', '채널 명', '스트리밍 시작 시간', '댓글 작성자', '댓글 내용', '댓글 작성 시간']) empty_frame.to_csv('./youtube.csv') chat = LiveChat(video_id=video_id, topchat_only='FALSE') while chat.is_alive(): try: data = chat.get() items = data.items for c in items: print(f"{c.datetime} [{c.author.name}]- {c.message}") data.tick() data2 = { '제목': [title], '채널 명': [author], '스트리밍 시작 시간': [published], '댓글 작성자': [c.author.name], '댓글 내용': [c.datetime], '댓글 작성 시간': [c.message]