python - discord.py on_message 在放弃 linux 作业并断开连接后停止工作

标签 python linux discord.py

我正在用 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 就会失败。

我可以想到一些您可以尝试的解决方案:

  1. 改用nohup(这是最交 key 的解决方案)
  2. stdout(可能还有 stderr)重定向到其他文件
  3. 通过传递 file= 参数将 打印到 stdout 之外的地方
  4. 使用logging 处理您的日志,不要将它们打印到stdout(参见Setting Up Logging)

关于python - discord.py on_message 在放弃 linux 作业并断开连接后停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56177079/

相关文章:

linux - while 循环后为空数组

Python Bot 按顺序发送消息

python - 使用 Discord.py 重写创建计数器机器人 - 分配错误之前引用的局部变量 'counter'

python - 在 python GUI 中实现 python 函数

python - 将 PNG 图像编码为 Base64 时出现 AttributeError

python - Django REST 框架 API : PrimaryKeyRelatedField

python - (discord.py) 如何让我的机器人随机回复 DM?

python - 类似 django 的集成不起作用

php - 警告:mysqli::mysqli(): header 和客户端库次要版本不匹配

linux - 配方文件安装在不同的目录