我试图做到这一点,以便我的机器人一次只能连接到 Discord,而另一个仅在另一个未连接时才连接。我怎样才能做到这一点?我在用着不和谐.py https://pypi.org/project/discord.py/。另外,如果可能的话,我希望它能够在多台机器上工作。
如果您问的是我认为您在问的问题,也就是说,机器人在任何时候都应该只允许在计算机上运行其自身的一个版本,那么这应该适用于您只想拥有的所有情况一次运行的脚本之一。
我们可以做到这一点的一种方法是让脚本创建一个“锁定”文件,如果该文件已经存在则退出。请记住在完成后将其删除,即使机器人崩溃了。
(这里可能有更好的方法来处理错误,并且您的机器人代码本身应该尽力处理机器人可能生成的错误。在大多数情况下,即使出现错误,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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)