【问题标题】:Python Bot keep running forever [duplicate]Python Bot永远运行[重复]
【发布时间】:2019-01-21 03:50:04
【问题描述】:

如果机器人随时崩溃,如何让我的机器人永远运行。

我在 linux 服务器上使用puttyscreen 中运行这个 ma​​in.py 文件,但我需要运行另一个文件来检查这个 main.py 文件是否每 30 分钟运行一次,如果没有它应该重新启动 main.py 文件。

所以下面是我的 ma​​in.py

import discord
from discord.ext import commands
from discord.ext.commands import Bot

bot = commands.Bot(command_prefix='!')

@bot.event
async def on_ready():
    print (bot.user.name)
    print (bot.user.id)
    print ("_____")

@bot.command(pass_context=True)
async def first(ctx):
     await bot.say("Hello {}".format(ctx.message.author.mention))

bot.run("XXXXXXXXXXXXXXXXXXXXXXXXXXXXX")

【问题讨论】:

    标签: python-3.x discord.py


    【解决方案1】:

    注意:我的回答以更通用的方式解决了这个问题。如果您的问题涉及不和谐机器人,this answer 提供了更好的解决方案。


    原答案:

    您可以将对程序的调用封装到 bash 脚本中。举个例子:

    #!/bin/bash
    
    while true
    do
      sleep 0.5
      ./bot # your program
      echo "[$(date)] bot exited with code $?. restarting ..."
    done
    

    上面的脚本会在退出时重新启动您的程序。但如果我是你,我会加入一个检查,如果你的脚本不断崩溃,它会停止重新启动。

    #!/bin/bash
    
    FAILS=0
    
    while true
    do
      sleep 0.5
      ./bot # your program
      EXIT=$?
      ((FAILS++))
    
      if [[ $FAILS -gt 10 ]]
      then
        echo "[$(date)] failed to many times. aborting ..."
        exit 1
      fi
    
      echo "[$(date)] bot exited with code $EXIT. restarting ..."
    
    done
    

    【讨论】:

    • 好的,谢谢。最后一个问题像main.py crashs 有没有机会让runforever.sh 崩溃,对不起一个愚蠢的问题。
    • 我现在有问题。 bot 不会退出 我试过 CTRL C 我收到一条消息 bot exited with code 0. restarting ... 并且 bot 突然重启。
    • 得到了解决方案,所以我可以解决这个问题?
    • 好的,现在它只停止 5 秒然后重新开始。所以它不能永久停止。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 2021-06-18
    • 2018-11-30
    • 2018-09-30
    • 1970-01-01
    • 2022-01-23
    • 2013-12-08
    相关资源
    最近更新 更多