def videoIDCallback(*args): global killThread shortenedID = videoID.get()[0:11] videoID.set(shortenedID) if len(videoID.get()) < 11: lbl_status["text"] = "Waiting for valid Video ID" lbl_status["bg"] = "#FF8888" killThread = True return try: global chat chat = pytchat.create(video_id=videoID.get()) except pytchat.exceptions.InvalidVideoIdException: lbl_status["text"] = "The specified ID was not found." killThread = True return if chat.is_alive(): lbl_status["text"] = "Connected, listening for messages from specified username" lbl_status["bg"] = "#91FF81" killThread = False thread_checkChat = threading.Thread(target=checkForMessage) thread_checkChat.start()
def test_speed_1(): stream = pytchat.create("Hj-wnLIYKjw", seektime=6000, processor=SpeedCalculator()) while stream.is_alive(): speed = stream.get() assert speed > 100 break
async def get(videoId: str, startAt: int, stopAt: str): messages = [] chat = pytchat.create(videoId, seektime=startAt) # while chat.is_alive(): data = chat.get() for c in data.items: message = f"{c.elapsedTime}-{c.message}" messages.append(message) if stopAt.replace("_", ":") in message: return messages
def reading_chat(self): chat = pytchat.create(video_id='Live Id') while chat.is_alive(): for c in chat.get().sync_items(): if c.message == 'd' or c.message == 'a' or c.message == 's' or c.message == 'w' or c.message == 'space': self.keyboard.press(c.message) time.sleep(0.2) self.keyboard.release(c.message) else: continue
def main(link, minutes): writer = csv.writer(sys.stdout, dialect='unix', quoting=csv.QUOTE_MINIMAL) chat = pytchat.create(video_id=link) end_time = time.time() + (minutes * 60) writer.writerow(['date-time', 'author', 'message']) while chat.is_alive() and time.time() < end_time: msg = chat.get().sync_items() for m in msg: writer.writerow([m.datetime, m.author.name, m.message]) return 1
def fillGlobals(): global livechat_id global broadcastId global pytchatObj #livechat_id = get_live_chat_id_for_stream_now(credentials) livechat_id = get_live_chat_id_for_stream_now() printBetter(f"livechat_id: {livechat_id}") #print(livechat_id) broadcastId = get_broadcastId() printBetter(f"broadcastId: {broadcastId}") #print(broadcastId) pytchatObj = pytchat.create(video_id=broadcastId)
def test_compatible_processor(): stream = pytchat.create("Hj-wnLIYKjw", seektime=6000, processor=CompatibleProcessor()) while stream.is_alive(): chat = stream.get() for key in chat.keys(): assert key in root_keys for key in chat["items"][0].keys(): assert key in item_keys for key in chat["items"][0]["snippet"].keys(): assert key in snippet_keys for key in chat["items"][0]["authorDetails"].keys(): assert key in author_details_keys break
def run(self): livechat = pytchat.create(self.video_id) while livechat.is_alive(): chatdata = livechat.get() for c in chatdata.sync_items(): print( f"{c.datetime} [{c.author.name}] {c.message} {c.amountString}" ) try: livechat.raise_for_status() except (ChatDataFinished, NoContents): print("Chat finished.") except Exception as e: print(type(e), str(e))
def Conectar(self, ID_Youtube): if(ID_Youtube != ''): print(f"Intentando Conectar a https://youtu.be/{ID_Youtube}") self.ID_Youtube = ID_Youtube # TODO: Agregar try try: self.chat = pytchat.create(video_id=self.ID_Youtube) self.conectado = True self.HiloChat = threading.Thread(target=self.Actualizar, daemon=True) self.HiloChat.start() print("Conectado ChatYoutube") except: print("No se puedo conectar Chat de Youtube") self.conectado = False else: self.conectado = False
def urlstart(): global idx, image, chat url2 = url.get() id = re.findall( r"(youtu\.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*)", url2 ) try: id = id[0][1] url.set(id) chat = pytchat.create(video_id=id) B1['state'] = 'disabled' E1['state'] = 'disabled' L2.config(text="") thread(chat_update) except: url.set('') L2.config(text="Enter Valid URL") pass
def fillGlobals(): global livechat_id global broadcastId global pytchatObj #livechat_id = get_live_chat_id_for_stream_now(credentials) livechat_id = get_live_chat_id_for_stream_now() printBetter(f"livechat_id: {livechat_id}") #print(livechat_id) ####################### ### pytchat stuff ### # NEEDS TESTING ONCE QUOTA RESETS #broadcastId = get_broadcastId(credentials) broadcastId = get_broadcastId() printBetter(f"broadcastId: {broadcastId}") #print(broadcastId) #broadcastId = "Ww6QEItZtUs" pytchatObj = pytchat.create(video_id=broadcastId)
def get_youtube_live_chat(video_id, excel_file_name): chat = pytchat.create(video_id=video_id) result = pd.DataFrame() while chat.is_alive(): for c in chat.get().sync_items(): print(f"{c.datetime} [{c.author.name}]- {c.message}") data = { '작성시간': [c.datetime], '작성자': [c.author.name], '채팅 내용': [c.message] } in_result = pd.DataFrame(data) result = result.append(in_result) result.to_excel( f'{BASE_DIR}/website/static/datas/reborn_show/{excel_file_name}', index=False, header=False, encoding='utf-8-sig', sheet_name='Sheet1')
def test_archived_stream(): for case in cases: stream = pytchat.create(video_id=case["video_id"], seektime=case["seektime"]) while stream.is_alive(): chat = stream.get() agg1 = {} agg2 = {} for c in chat.items: if c.type in agg1: agg1[c.type] += 1 else: agg1[c.type] = 1 if c.author.type in agg2: agg2[c.author.type] += 1 else: agg2[c.author.type] = 1 break assert agg1 == case["result1"] assert agg2 == case["result2"]
async def on_slash_livetlstream(ctx: discord_slash.SlashContext, link: str, filterlang: str = None): if ctx.author.voice is None: await ctx.send("You're not in a voice channel.") elif ctx.guild.voice_client is None: await ctx.send("I'm not in a voice channel.") elif ctx.guild.voice_client.channel == ctx.author.voice.channel: id_index = -1 if 'youtube.com' in link: id_index = link.find('v=') + 2 elif 'youtu.be' in link: id_index = link.find('/') + 1 if id_index == -1: await ctx.send("Invalid link") return await ctx.send("Starting livetl stream") try: room = pyt.create(video_id=link[id_index:id_index + 11]) except: await ctx.send("Not Live") return while room.is_alive(): for x in room.get().sync_items(): if ctx.guild.voice_client.channel is None: return if (the_real_message := parseTranslation(x)) is not None: if filterlang is None or filterlang.lower( ) in the_real_message[0].lower(): with open(tts(the_real_message[1])) as f: ctx.guild.voice_client.play( discord.FFmpegPCMAudio(f, pipe=True)) while ctx.guild.voice_client and ctx.guild.voice_client.is_playing( ): await asyncio.sleep(1) os.remove(f.name) return
def get(): try: print("proba") link = e1.get() print("dziala") link = link[32:43] print(link) chat = pytchat.create(video_id=link) while chat.is_alive(): print("chat alive") for c in chat.get().sync_items(): print("proba") try: print(c.message) i = c.message value = write_read(i) print(value) except: print("pass") pass print("chat not alive") except: print("main get error") pass
import pytchat Video_id = "123456" chat = pytchat.create(video_id=Video_id) while chat.is_alive(): for c in chat.get().sync_items(): if c.author.isChatOwner: print(f"Creador: {c.datetime} [{c.author.name}]- {c.message}") elif c.author.isChatSponsor: print(f"Miembro: {c.datetime} [{c.author.name}]- {c.message}") elif c.author.isChatModerator: print(f"Moderador: {c.datetime} [{c.author.name}]- {c.message}")
CHANNEL = 'possandglor' # input("Channel: ") msgs = [] chnls = [] pisun = {} iqs = {} def send_message(chnnl, message): print( str(datetime.now().strftime("%H:%M:%S")) + " \033[1;32;40m " + chnnl + ": " + NICK + "\033[0;37;40m: " + message) s.send(bytes("PRIVMSG #" + chnnl + " :" + message + "\r\n", "UTF-8")) chat = pytchat.create(video_id="m3l94vZdUA0") class YoutubeGetter(Thread): def __init__(self, name): """Инициализация потока""" Thread.__init__(self) self.name = name def run(self): while chat.is_alive(): mes = chat.get().json() mes = json.loads(mes) # print(mes) author = "" message = ""
import pytchat import pytchat videoId = input('Enter YouTube Video ID: ') f = open(f'outputs/{videoId}.txt', 'w') chat = pytchat.create(video_id=videoId) while chat.is_alive(): for c in chat.get().items: obj = c.json() obj2 = json.loads(obj) f.write(str("{} {}: {}".format(obj2['author']['name'], obj2['datetime'],obj2['message']).encode('utf8'))) f.write("\n") f.close()
import pytchat import time # PytchatCoreオブジェクトの取得 video_id = "zCK_490ryjg" ''' "zCK_490ryjg" キズナアイから大事なお知らせがあります "9u_I1k65MYE" 【空気読み。】読めるんです!ほんとです!ぺこ!【ホロライブ/兎田ぺこら】 "I1wqOXlXHp8" 公園の地下に巨大神殿があるらしいので行ってみた【にじさんじ/月ノ美兎】 ''' livechat = pytchat.create(video_id) # video_idはhttps://....watch?v=より後ろの filepath = "./comment_{}.txt".format(video_id) with open(filepath, mode='a') as f: while livechat.is_alive(): # チャットデータの取得 chatdata = livechat.get() for c in chatdata.items: f.write(f"{c.datetime}|,|{c.author.name}|,|{c.message}\n") ''' JSON文字列で取得: # print(c.json()) ''' time.sleep(5)
from gtts import gTTS import os import pytchat youtube_id = os.environ['YOUTUBE_ID'] youtube = pytchat.create(video_id=youtube_id) def speech(text): t2s = gTTS(text=text, lang='es', slow=False) t2s.save("youtube.mp3") os.system("mpg321 --stereo youtube.mp3") if __name__ == '__main__': while True: for comment in youtube.get().sync_items(): speech( str(comment.author.name) + ' dice ' + str(comment.message) + ' desde YouTube') print( str(comment.author.name) + ' dice ' + str(comment.message) + ' desde YouTube')
if q.empty() == False: command = q.get() with open("messages.log", "a") as f: f.write(f"{command} \n") commanddict[command]() else: time.sleep(0.25) # Starting the CmdQueue as Process so the chat getting shit can do its job. p = Process(target=CmdQueue) p.start() # Getting chat shit chat = pytchat.create(video_id=data["id"]) while chat.is_alive(): for c in chat.get().sync_items(): if commanddict.get(c.message, "nocmd") != "nocmd": if timemessage.get(c.author.name, 1) == 1: #print(f"New user {c.author.name}") #print(f"{c.message} from {c.author.name}. \n") q.put(c.message) timemessage.update({c.author.name: int(time.time())}) elif (int(time.time()) - timemessage.get(c.author.name, 1)) < 5: print(f"{c.author.name} - Timeout") elif (int(time.time()) - timemessage.get(c.author.name, 1)) >= 5: print(f"{c.author.name} - {c.message}") q.put(c.message)
# Creado ChepeCarlos de ALSW # Tutorial Completo en https://nocheprogramacion.com # Canal Youtube https://youtube.com/alswnet?sub_confirmation=1 import pytchat chat = pytchat.create(video_id="123456") while chat.is_alive(): for c in chat.get().sync_items(): print(f"{c.datetime} [{c.author.name}]- {c.message}")
"Deadline and Xamfear stepped out and so I started a live stream") if (idlemessage == 6): clickysay( "You can interact with me through the chat, just make sure to address me as in Clicky, question?" ) if (idlemessage == 7): clickysay("Where has Amy gone off to?") if (idlemessage == 14): clickysay("Please like and subscr I buh!") if (idlemessage == 20): idlemessage = 0 chat = pytchat.create(video_id=videostreamid, interruptable=True) if (chat.is_alive() == False): os.system("sam Bummer man!") print("Can not find that live stream") exit(1) users = {} idle = 0 nextidletime = random.randint(1, 30) system('cls') print("CityXen Clicky Live Alpha Testing.") print("Welcome! Please chat with Clicky.")
#-*- coding: utf-8 -*- import pytchat import time # 추출하고 싶은 단어 있으면 여기 입력, 여러개면 리스트로 만들고 아래 반복문 추가 targetStr = "" URL = input("URL 입력: ") chat = pytchat.create(video_id=URL) # 날짜 형식 tm = time.localtime() year = str(tm.tm_year)[2:] month = str(tm.tm_mon) day = str(tm.tm_mday) if len(month) == 1: month = '0' + month if len(day) == 1: day = '0' + day def getName(name): return name def getMsg(msg): return msg while chat.is_alive(): for c in chat.get().sync_items(): name, message = "", "" # targetStr이 이름에 있으면 추출 if targetStr in c.author.name:
time.sleep(5 - ((time.time() - starttime) % 5)) avg = sum(messages)/len(messages) if avg > 0: avg = str(avg) + " Good" elif avg < 0: avg = str(avg) + " Bad" else: avg = str(avg) + " Neutral" print( "\n\n", time.asctime(time.localtime(starttime)), " - ", time.asctime(time.localtime(time.time())), "\n", avg, "\n\n" ) messages.clear() if __name__ == "__main__": time_thread = threading.Thread(target=timer) time_thread.start() chat = pytchat.create(video_id="RMZ1a6I86l0") while chat.is_alive(): for c in chat.get().sync_items(): text = TextBlob(c.message) print(f"{round(text.sentiment.polarity, 2)} [{c.author.name}] - {c.message}") messages.append(text.sentiment.polarity)