检查 Discord 机器人是否在线

Com*_*Dev 5 python discord discord.py

我正在尝试使我的机器人一次只能连接到一个实例,而另一个实例仅在另一个未连接时连接。我怎么能做到这一点?我正在使用Discord.py。另外,如果可能的话,我希望它可以在多台机器上工作。

ch4*_*e97 1

如果您问的是我认为您在问的问题,也就是说,机器人在任何时候都应该只允许在计算机上运行其自身的一个版本,那么这应该适用于您只想拥有的所有情况一次运行的脚本之一。

我们可以做到这一点的一种方法是让脚本创建一个“锁定”文件,如果该文件已经存在则退出。请记住在完成后将其删除,即使机器人崩溃了。(这里可能有更好的方法来处理错误,并且您的机器人代码本身应该尽力处理机器人可能生成的错误。在大多数情况下,即使出现错误,discord.py 也会继续运行。这只会得到严重的机器人崩溃问题,并确保您可以看到发生了什么,同时仍然优雅地关闭并确保锁定文件被删除。)

import discord
from discord.ext import commands
import os  # for file interactions
import traceback
# etc.

bot = commands.Bot(description="Hard Lander's lovely bot", command_prefix="!")
@bot.event
async def on_ready():
    print("I'm ready to go!")
    print(f"Invite link: https://discordapp.com/oauth2/authorize?client_id={bot.user.id}&scope=bot&permissions=8")

def main():
    bot.run("TOKEN")

if __name__ == '__main__':
    running_file = "running.txt"
    if os.path.isfile(running_file):  # check if the "lock" file exists
        print("Bot already running!")
        exit()  # close this instance having taken no action. 
    else:
        with open(running_file, 'w') as f:
            f.write("running")
    try:  # catch anything that crashes the bot
        main()
    except:  # print out the error properly 
        print(traceback.format_exc())
    finally:  # delete the lock file regardless of it it crashed or closed naturally. 
        os.unlink(running_File)
        
Run Code Online (Sandbox Code Playgroud)