首页 > 解决方案 > 等待python中的值更改

问题描述

我正在 ping 一个带有不和谐机器人设置的服务器的 IP。我希望它在 ping 的输出从 1 变为 0 时发送一条消息,这意味着服务器已离线,但在我当前的设置中,它只是一个 while 循环,它会一遍又一遍地发送消息,但我只希望它每当状态1变为0时发送 1 条消息

@tasks.loop()
async def serverstatus():
    channel=bot.get_channel(850531139403776040)
    status=os.system("ping -c 1 "+ip)
    messagesent=0
    if status==0:
        await channel.send(f"<@&850539902675845170> Server Offline")
    else:
        await channel.send("Server Online")

标签: pythondiscorddiscord.py

解决方案


was_online = True
@tasks.loop()
async def serverstatus():
    global was_online
    channel = bot.get_channel(850531139403776040)
    is_online = os.system("ping -c 1 "+ip)
    if was_online and not(is_online):           
       await channel.send(
           f"<@&850539902675845170> Server Offline")      
    else:
        await channel.send("Server Online")
    was_online = is_online

如果您想在离线后退出循环:

@tasks.loop()
async def serverstatus():
    channel=bot.get_channel(850531139403776040)
    status=os.system("ping -c 1 "+ip)
    if status:
        await channel.send("Server Online")  
    else:
        await channel.send(f"<@&850539902675845170> Server Offline")
        serverstatus.stop()

推荐阅读