upate
This commit is contained in:
+70
-37
@@ -419,51 +419,84 @@ class TwitchChatBot:
|
||||
self.channel = channel.lower()
|
||||
self.messages: List[ChatMessage] = []
|
||||
self.uri = "wss://irc-ws.chat.twitch.tv:443"
|
||||
self.is_running = True
|
||||
self.script_name = "TwitchChat"
|
||||
self.chat_thread = None
|
||||
self.loop = None
|
||||
|
||||
def get_last_message(self) -> Optional[ChatMessage]:
|
||||
return self.messages[-1] if self.messages else None
|
||||
|
||||
def get_all_messages(self) -> List[ChatMessage]:
|
||||
return self.messages
|
||||
def stop(self):
|
||||
sprint(self.script_name, "red", f"Arrêt de la connexion au chat")
|
||||
self.is_running = False
|
||||
if self.loop and self.loop.is_running():
|
||||
self.loop.call_soon_threadsafe(self.loop.stop)
|
||||
if self.chat_thread and self.chat_thread.is_alive():
|
||||
self.chat_thread.join(timeout=2) # Attendre max 2 secondes
|
||||
sprint(self.script_name, "red", "Connexion au chat arrêtée.")
|
||||
else:
|
||||
sprint(self.script_name, "yellow", f"Connexion au chat déjà arrêtée")
|
||||
|
||||
async def connect_to_twitch_chat(self):
|
||||
async with websockets.connect(self.uri) as websocket:
|
||||
# Se connecter en tant qu'utilisateur anonyme
|
||||
await websocket.send("CAP REQ :twitch.tv/tags twitch.tv/commands")
|
||||
await websocket.send(f"NICK justinfan{random.randint(10000,99999)}")
|
||||
await websocket.send(f"JOIN #{self.channel}")
|
||||
while self.is_running:
|
||||
try:
|
||||
async with websockets.connect(self.uri) as websocket:
|
||||
await websocket.send("CAP REQ :twitch.tv/tags twitch.tv/commands")
|
||||
await websocket.send(f"NICK justinfan{random.randint(10000,99999)}")
|
||||
await websocket.send(f"JOIN #{self.channel}")
|
||||
|
||||
print(f"✅ Connecté au chat de #{self.channel}")
|
||||
sprint(self.script_name, "green", f"Connecté au chat de #{self.channel}")
|
||||
|
||||
while True:
|
||||
try:
|
||||
message = await websocket.recv()
|
||||
if "PRIVMSG" in message:
|
||||
# Extraction des données du message
|
||||
user = message.split("!", 1)[0][1:]
|
||||
if "display-name=" in user:
|
||||
user = user.split("display-name=")[1].split(";")[0]
|
||||
else:
|
||||
user = user.lower()
|
||||
|
||||
msg = message.split("PRIVMSG", 1)[1].split(":", 1)[1]
|
||||
timestamp = datetime.now()
|
||||
|
||||
# Création et stockage du message
|
||||
chat_message = ChatMessage(timestamp=timestamp, username=user, content=msg)
|
||||
self.messages.append(chat_message)
|
||||
|
||||
# Affichage formaté
|
||||
time_str = timestamp.strftime("%H:%M:%S.%f")[:-3]
|
||||
print(f"[\033[95m{time_str}\033[0m] \033[94m{user}\033[0m: \033[92m{msg}\033[0m")
|
||||
while self.is_running:
|
||||
try:
|
||||
message = await websocket.recv()
|
||||
if "PRIVMSG" in message:
|
||||
user = message.split("!", 1)[0][1:]
|
||||
if "display-name=" in user:
|
||||
user = user.split("display-name=")[1].split(";")[0]
|
||||
else:
|
||||
user = user.lower()
|
||||
|
||||
msg = message.split("PRIVMSG", 1)[1].split(":", 1)[1]
|
||||
timestamp = datetime.now()
|
||||
|
||||
chat_message = ChatMessage(timestamp=timestamp, username=user, content=msg)
|
||||
self.messages.append(chat_message)
|
||||
|
||||
time_str = timestamp.strftime("%H:%M:%S.%f")[:-3]
|
||||
sprint(self.script_name, "magenta", f"[{time_str}] {user}: {msg}")
|
||||
|
||||
except websockets.exceptions.ConnectionClosed:
|
||||
print("\033[91m⚠️ Connexion fermée, reconnexion en cours...\033[0m")
|
||||
break
|
||||
except websockets.exceptions.ConnectionClosed:
|
||||
sprint(self.script_name, "yellow", "⚠️ Connexion fermée, tentative de reconnexion...")
|
||||
break
|
||||
|
||||
def start(self):
|
||||
asyncio.run(self.connect_to_twitch_chat())
|
||||
except Exception as e:
|
||||
sprint(self.script_name, "red", f"Erreur de connexion: {str(e)}")
|
||||
if self.is_running:
|
||||
await asyncio.sleep(5)
|
||||
|
||||
def run_chat_loop(self):
|
||||
try:
|
||||
self.loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(self.loop)
|
||||
self.loop.run_until_complete(self.connect_to_twitch_chat())
|
||||
except Exception as e:
|
||||
if self.is_running: # Ignorer les erreurs pendant l'arrêt
|
||||
sprint(self.script_name, "red", f"Erreur dans la boucle du chat: {str(e)}")
|
||||
finally:
|
||||
try:
|
||||
if self.loop and self.loop.is_running():
|
||||
self.loop.close()
|
||||
except:
|
||||
pass
|
||||
|
||||
def start_background(self):
|
||||
"""Lance la connexion au chat dans un thread séparé"""
|
||||
self.is_running = True
|
||||
self.chat_thread = threading.Thread(target=self.run_chat_loop)
|
||||
self.chat_thread.daemon = True
|
||||
self.chat_thread.start()
|
||||
|
||||
self.chat_thread = threading.Thread(target=self.main_loop)
|
||||
self.chat_thread.start() # Démarre dans un thread séparé
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user