You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Repl.it上的Python脚本向在线Windows PC发送通知?

实现方案:Repl.it 24/7运行脚本并向在线Windows PC发送通知

一、让Repl.it脚本保持24/7运行

Repl.it免费实例会在无交互一段时间后休眠,需通过以下方式维持运行:

  • 给脚本添加简单Web服务(用Flask),配合外部监控工具定期发送请求唤醒实例。
  • 核心代码示例:
from flask import Flask
import threading
import time

app = Flask(__name__)

@app.route('/')
def home():
    return "Script is running!"

def run_flask():
    app.run(host='0.0.0.0', port=3000)

# 启动Flask后台线程
threading.Thread(target=run_flask).start()

# 主逻辑循环
while True:
    check_condition_and_notify()
    time.sleep(60)  # 每分钟执行一次检测
  • 用外部监控工具每隔5-10分钟向Repl.it实例的URL发送HTTP请求,防止实例休眠。

二、检测Windows PC在线状态

提供两种可靠方案:

方式1:Ping检测

通过Python执行ping命令判断PC可达性(需Windows防火墙允许ICMP请求):

import subprocess
import platform

def is_pc_online(ip_address):
    param = '-n' if platform.system().lower() == 'windows' else '-c'
    command = ['ping', param, '1', ip_address]
    return subprocess.call(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0

方式2:端口连接检测

在Windows PC上运行监听脚本,Repl.it通过连接指定端口判断在线状态(不受防火墙ping限制):
PC端监听脚本:

import socket

HOST = '0.0.0.0'
PORT = 12345

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    while True:
        conn, addr = s.accept()
        with conn:
            conn.sendall(b'Online')
            conn.close()

Repl.it端检测代码:

import socket

def is_pc_online(ip_address, port=12345):
    try:
        with socket.create_connection((ip_address, port), timeout=5):
            return True
    except (socket.timeout, ConnectionRefusedError):
        return False

三、向Windows PC发送通知

方式1:本地服务触发Toast通知

在Windows PC的监听脚本中,收到Repl.it的通知请求后弹出系统Toast:
PC端完整脚本(监听+通知):

import socket
from win10toast import ToastNotifier

HOST = '0.0.0.0'
PORT = 12345
toaster = ToastNotifier()

def show_notification(title, message):
    toaster.show_toast(title, message, duration=10)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    print(f"Listening on port {PORT}...")
    while True:
        conn, addr = s.accept()
        with conn:
            data = conn.recv(1024).decode('utf-8')
            if data.startswith('NOTIFY:'):
                title, message = data.split(':', 2)[1], data.split(':', 2)[2]
                show_notification(title, message)
            conn.sendall(b'Notification received')

Repl.it端发送通知代码:

import socket

def send_notification(ip_address, port=12345, title="Alert", message="Condition met!"):
    try:
        with socket.create_connection((ip_address, port), timeout=5) as s:
            s.sendall(f"NOTIFY:{title}:{message}".encode('utf-8'))
            return True
    except Exception as e:
        print(f"Failed to send notification: {e}")
        return False

方式2:邮件通知(备选)

若不想运行本地脚本,可通过SMTP发送邮件,配合Windows邮件客户端的通知提醒:

import smtplib
from email.mime.text import MIMEText

def send_email_notification():
    sender_email = "your-repl-email@example.com"
    receiver_email = "your-windows-email@example.com"
    password = "your-app-specific-password"

    msg = MIMEText("Your target condition has been triggered!")
    msg['Subject'] = "Alert: Condition Met"
    msg['From'] = sender_email
    msg['To'] = receiver_email

    with smtplib.SMTP_SSL('smtp.example.com', 465) as server:
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver_email, msg.as_string())

四、整合核心逻辑

将各部分整合到Repl.it主脚本:

from flask import Flask
import threading
import time
import socket

app = Flask(__name__)

@app.route('/')
def home():
    return "Script is active!"

def run_flask():
    app.run(host='0.0.0.0', port=3000)

threading.Thread(target=run_flask).start()

# 配置PC信息
PC_IP = "192.168.1.100"  # 替换为你的PC公网/内网IP
PC_PORT = 12345

def is_pc_online():
    try:
        with socket.create_connection((PC_IP, PC_PORT), timeout=5):
            return True
    except:
        return False

def send_notification():
    try:
        with socket.create_connection((PC_IP, PC_PORT), timeout=5) as s:
            s.sendall("NOTIFY:Condition Alert:Target value is now True!".encode('utf-8'))
            print("Notification sent successfully")
    except Exception as e:
        print(f"Failed to send notification: {e}")

def check_condition_and_notify():
    # 替换为你的实际条件判断逻辑
    target_value = get_your_target_value()
    if target_value and is_pc_online():
        send_notification()

def get_your_target_value():
    # 示例:模拟值变化,实际场景可为API请求、数据库查询等
    import random
    return random.choice([True, False])

# 主循环
while True:
    check_condition_and_notify()
    time.sleep(60)

注意事项

  • Windows PC需设置静态IP或使用DDNS,确保Repl.it能访问到;若在局域网内,需在路由器上设置端口转发。
  • 安装依赖:Repl.it端执行pip install flask,Windows PC端执行pip install win10toast。

内容的提问来源于stack exchange,提问作者NitroX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 03:09:14