fmab777 commited on
Commit
a4284b2
·
verified ·
1 Parent(s): 9332201

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +22 -18
main.py CHANGED
@@ -933,17 +933,24 @@ logger.info(f"Bot setup finished. Application instance: {'OK' if ptb_app else 'F
933
 
934
 
935
  # --- Flask App Setup (for Webhook) ---
936
- app = Flask(__name__)
937
- logger.info("Flask app created.")
938
 
939
- @app.route('/')
 
 
 
 
 
 
 
940
  def index():
941
  """Basic health check endpoint."""
942
  logger.debug("Health check '/' accessed.")
943
  bot_status = "Initialized" if ptb_app and ptb_app.bot else "Initialization FAILED"
944
  return f"Telegram Bot Webhook Listener ({bot_status}) is running."
945
 
946
- @app.route('/webhook', methods=['POST'])
947
  async def webhook() -> Response:
948
  """Webhook endpoint for Telegram updates."""
949
  if not ptb_app:
@@ -956,13 +963,8 @@ async def webhook() -> Response:
956
  update_data = request.get_json()
957
  update = Update.de_json(update_data, ptb_app.bot)
958
  logger.debug(f"Processing update ID: {update.update_id} via webhook")
959
-
960
- # Crucial: Queue the update for processing by PTB's internal mechanisms
961
- # This ensures proper handling within PTB's async context
962
- # Use await ptb_app.process_update(update) directly as Flask is run by Uvicorn
963
  await ptb_app.process_update(update)
964
  logger.debug(f"Finished processing update ID: {update.update_id}")
965
-
966
  return Response('ok', status=200) # Acknowledge receipt to Telegram
967
 
968
  except json.JSONDecodeError:
@@ -970,24 +972,26 @@ async def webhook() -> Response:
970
  return Response('Bad Request: Invalid JSON', status=400)
971
  except Exception as e:
972
  logger.error(f"Error processing update in webhook: {e}", exc_info=True)
973
- # Avoid sending detailed errors back in the response
974
  return Response('Internal Server Error processing update.', status=500)
975
  else:
976
  logger.warning("Received non-JSON request to webhook endpoint.")
977
  return Response('Bad Request: Expected JSON', status=400)
978
 
 
 
 
 
 
 
979
  # --- Main Execution Block (for local testing ONLY) ---
980
  if __name__ == '__main__':
981
- # This block is NOT used when running with Gunicorn/Uvicorn in production
 
982
  logger.warning("Running Flask development server directly (for local testing only).")
983
  if not ptb_app:
984
  logger.critical("Aborting local Flask start: Telegram App (ptb_app) failed initialization.")
985
  else:
986
- # For local testing, you might need to set a webhook manually or use polling.
987
- # Flask's dev server can work with asyncio now.
988
- # Running with debug=True enables auto-reloading and more detailed errors.
989
- local_port = int(os.environ.get('PORT', 8080)) # Use a different port locally?
990
  logger.info(f"Flask dev server starting on http://0.0.0.0:{local_port}")
991
- # Note: Flask's built-in server is NOT recommended for production.
992
- # Use Gunicorn + Uvicorn worker as configured in gunicorn.conf.py for deployment.
993
- app.run(host='0.0.0.0', port=local_port, debug=True)
 
933
 
934
 
935
  # --- Flask App Setup (for Webhook) ---
936
+ # Import the WSGI-to-ASGI bridge
937
+ from asgiref.wsgi import WsgiToAsgi
938
 
939
+ logger.info("Flask app setup initiating...")
940
+
941
+ # Create the core Flask app instance (give it a distinct name)
942
+ flask_app = Flask(__name__)
943
+ logger.info("Core Flask app instance created.")
944
+
945
+ # --- Define Flask Routes on flask_app ---
946
+ @flask_app.route('/')
947
  def index():
948
  """Basic health check endpoint."""
949
  logger.debug("Health check '/' accessed.")
950
  bot_status = "Initialized" if ptb_app and ptb_app.bot else "Initialization FAILED"
951
  return f"Telegram Bot Webhook Listener ({bot_status}) is running."
952
 
953
+ @flask_app.route('/webhook', methods=['POST'])
954
  async def webhook() -> Response:
955
  """Webhook endpoint for Telegram updates."""
956
  if not ptb_app:
 
963
  update_data = request.get_json()
964
  update = Update.de_json(update_data, ptb_app.bot)
965
  logger.debug(f"Processing update ID: {update.update_id} via webhook")
 
 
 
 
966
  await ptb_app.process_update(update)
967
  logger.debug(f"Finished processing update ID: {update.update_id}")
 
968
  return Response('ok', status=200) # Acknowledge receipt to Telegram
969
 
970
  except json.JSONDecodeError:
 
972
  return Response('Bad Request: Invalid JSON', status=400)
973
  except Exception as e:
974
  logger.error(f"Error processing update in webhook: {e}", exc_info=True)
 
975
  return Response('Internal Server Error processing update.', status=500)
976
  else:
977
  logger.warning("Received non-JSON request to webhook endpoint.")
978
  return Response('Bad Request: Expected JSON', status=400)
979
 
980
+ # --- Wrap the Flask WSGI app into an ASGI app ---
981
+ # Gunicorn/Uvicorn will look for this 'app' object by default (main:app)
982
+ app = WsgiToAsgi(flask_app)
983
+ logger.info("Flask WSGI app wrapped with WsgiToAsgi for ASGI compatibility.")
984
+
985
+
986
  # --- Main Execution Block (for local testing ONLY) ---
987
  if __name__ == '__main__':
988
+ # This block remains the same, but note it runs the core flask_app
989
+ # using Flask's development server, NOT the wrapped ASGI app.
990
  logger.warning("Running Flask development server directly (for local testing only).")
991
  if not ptb_app:
992
  logger.critical("Aborting local Flask start: Telegram App (ptb_app) failed initialization.")
993
  else:
994
+ local_port = int(os.environ.get('PORT', 8080))
 
 
 
995
  logger.info(f"Flask dev server starting on http://0.0.0.0:{local_port}")
996
+ # Run the original Flask app for local dev server
997
+ flask_app.run(host='0.0.0.0', port=local_port, debug=True)