Enhance TwitchBot message sending by integrating event loop management. Updated send_twitch_message to utilize the existing event loop for asynchronous message sending, improving reliability and error handling. Added timeout handling for message sending operations.
This commit is contained in:
@@ -158,8 +158,10 @@ def _isConfigured():
|
||||
|
||||
class TwitchBot():
|
||||
_eventsub = None
|
||||
_loop = None
|
||||
|
||||
async def _connect(self):
|
||||
self._loop = asyncio.get_event_loop()
|
||||
with webapp.app_context():
|
||||
if _isConfigured():
|
||||
try:
|
||||
|
||||
+19
-29
@@ -287,24 +287,18 @@ def send_twitch_message():
|
||||
if not channel:
|
||||
return jsonify({"success": False, "error": "Channel Twitch non configuré"}), 400
|
||||
|
||||
# Envoyer le message de manière asynchrone
|
||||
try:
|
||||
if not twitchBot._loop:
|
||||
return jsonify({"success": False, "error": "Event loop du bot non disponible"}), 503
|
||||
|
||||
async def send_msg():
|
||||
try:
|
||||
await twitchBot.chat.send_message(channel, message)
|
||||
return True
|
||||
except Exception as e:
|
||||
return str(e)
|
||||
|
||||
# Exécuter la coroutine de manière synchrone
|
||||
loop = asyncio.new_event_loop()
|
||||
result = loop.run_until_complete(send_msg())
|
||||
loop.close()
|
||||
|
||||
if result is True:
|
||||
future = asyncio.run_coroutine_threadsafe(send_msg(), twitchBot._loop)
|
||||
future.result(timeout=10)
|
||||
return jsonify({"success": True})
|
||||
else:
|
||||
return jsonify({"success": False, "error": f"Erreur: {result}"}), 500
|
||||
except TimeoutError:
|
||||
return jsonify({"success": False, "error": "Timeout lors de l'envoi"}), 504
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
@@ -312,7 +306,7 @@ def send_twitch_message():
|
||||
@require_page("twitch_moderation")
|
||||
def get_twitch_messages():
|
||||
"""Retourne les derniers messages du chat Twitch"""
|
||||
messages = webapp.config["BOT_STATUS"].get("twitch_chat_messages", [])
|
||||
messages = list(webapp.config["BOT_STATUS"].get("twitch_chat_messages", []))
|
||||
return jsonify({"messages": messages})
|
||||
|
||||
|
||||
@@ -395,14 +389,14 @@ def execute_moderation_action():
|
||||
|
||||
admin_name = f"WebApp ({current_user.username})"
|
||||
|
||||
# Exécuter l'action de manière asynchrone
|
||||
try:
|
||||
if not twitchBot._loop:
|
||||
return jsonify({"success": False, "error": "Event loop du bot non disponible"}), 503
|
||||
|
||||
async def execute_action():
|
||||
try:
|
||||
if action == 'timeout':
|
||||
from twitchbot.moderation import _get_broadcaster_id, _get_moderator_id, _get_user_id, _log_action
|
||||
username = params.get('username', '').strip().lstrip('@')
|
||||
duration = int(params.get('duration', 600)) # en secondes
|
||||
duration = int(params.get('duration', 600))
|
||||
reason = params.get('reason', 'Timeout')
|
||||
|
||||
broadcaster_id = await _get_broadcaster_id(twitchBot.twitch, channel)
|
||||
@@ -452,7 +446,7 @@ def execute_moderation_action():
|
||||
elif action == 'permit':
|
||||
from database.models import TwitchPermit
|
||||
username = params.get('username', '').strip().lstrip('@').lower()
|
||||
duration = int(params.get('duration', 60)) # en secondes
|
||||
duration = int(params.get('duration', 60))
|
||||
|
||||
expires_at = datetime.now() + timedelta(seconds=duration)
|
||||
|
||||
@@ -492,19 +486,15 @@ def execute_moderation_action():
|
||||
|
||||
return {"success": False, "error": f"Action '{action}' non reconnue"}
|
||||
|
||||
try:
|
||||
future = asyncio.run_coroutine_threadsafe(execute_action(), twitchBot._loop)
|
||||
result = future.result(timeout=15)
|
||||
return jsonify(result)
|
||||
except TimeoutError:
|
||||
return jsonify({"success": False, "error": "Timeout lors de l'exécution"}), 504
|
||||
except Exception as e:
|
||||
import logging
|
||||
logging.error(f"Erreur lors de l'exécution de l'action {action}: {e}")
|
||||
return {"success": False, "error": str(e)}
|
||||
|
||||
# Exécuter la coroutine de manière synchrone
|
||||
loop = asyncio.new_event_loop()
|
||||
result = loop.run_until_complete(execute_action())
|
||||
loop.close()
|
||||
|
||||
return jsonify(result)
|
||||
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user