检查不和谐机器人是否在线 [英] Check if Discord bot is online

查看:24
本文介绍了检查不和谐机器人是否在线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试这样做,以便我的bot一次只有一个实例可以连接到Discorde,而另一个只有在另一个没有连接的情况下才能连接。我怎么才能做到这一点呢?我正在使用Discord.py。另外,如果可能的话,我希望它能跨多台计算机工作。

推荐答案

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

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

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)
        

这篇关于检查不和谐机器人是否在线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆