我正在用 python 编写一个 discord-bot,它可以在 IntelliJ 甚至终端上正常运行。
当我尝试让它在 linux 服务器上运行但未连接到它时,问题就开始了
# Called when a message is created and sent to a server.
# Parameters: message – A Message of the current message.
async def on_message(self, message):
print('Message from {0.author}: {0.content}'.format(message))
if message.author == self.user:
return
try:
await self.serverLog.on_message(message)
except Exception as e:
logger.exception(e)
try:
await self.werwolfBot.on_message(message)
except Exception as e:
logger.exception(e)
我通过命令行启动机器人
cd WerwolfBot
python3.6 -m werwolf &
disown
仍然通过 putty on_message 连接并且所有其他事件都会触发
当我断开与 linux 服务器的 ssh 连接时 从那一刻起,它将触发其他事件,例如 on_voice_state_update 但不会触发 on_message
我希望我可以让机器人运行 disowned 并且它仍然可以工作。但它只适用于 on_message 以外的其他事件
最佳答案
参见 this answer on Unix SE关于 disown
实际做了什么。这是与您的问题相关的部分:
However note that it still is connected to the terminal, so if the terminal is destroyed (which can happen if it was a pty, like those created by xterm or ssh, and the controlling program is terminated, by closing the xterm or terminating the SSH connection), the program will fail as soon as it tries to read from standard input or write to standard output.
因此,一旦 print
尝试写入 stdout
,您的 on_message
就会失败。
我可以想到一些您可以尝试的解决方案:
- 改用
nohup
(这是最交 key 的解决方案) - 将
stdout
(可能还有stderr
)重定向到其他文件 通过传递
打印到file=
参数将stdout
之外的地方- 使用
logging
处理您的日志,不要将它们打印到stdout
(参见Setting Up Logging)
关于python - discord.py on_message 在放弃 linux 作业并断开连接后停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56177079/