在 Ubuntu 上运行用 python 制作的 Telegram 机器人作为后台服务

问题描述 投票:0回答:1

无法将电报机器人作为后台服务运行。当直接从终端运行时 - 它工作正常。

我使用 Telebot 库制作了一个简单的电报机器人:

import telebot

TOKEN = '7121288866:AAEh_QvG2nJshSziHSSV0HMIr2D0ksjB0Bk'
bot = telebot.TeleBot(TOKEN)

@bot.message_handler(content_types=['text'])
def proc_msg(message):
    chat_id = message.chat.id
    bot.send_message(chat_id,text="I'm test bot. Sorry, can't answer anything else. Made for dummy tests.")

bot.polling(none_stop=True, interval=0)

当我通过终端运行脚本时它就起作用了:

python test_bot.py

我需要将机器人作为后台服务运行,并在重新启动后自动重新启动,所以我制作了 test_bot.service 文件:

[Unit]
Description=Test Bot
After=multi-user.target

[Service]
Type=simple
Restart=always
ExecStart=/usr/bin/python /etc/tg_bots/test4477qwe_bot/test_bot.py

[Install]
WantedBy=multi-user.target

然后将文件放入

/etc/systemd/system
并运行
systemctl daemon-reload
。在这个阶段一切都很好,我的服务在
systemctl

给出的列表中

但是当我尝试使用命令

systemctl start test_bot
运行服务时 - 什么也没有发生。它实际上看起来像
systemctl start test_bot
挂着。

可能出了什么问题? (系统是 Ubuntu 22.04.3 LTS。也许它不是运行 python-telegram-bots 的最佳选择?)

python telegram python-telegram-bot systemctl telebot
1个回答
0
投票

您可以使用此代码启动脚本,它将在后台运行。

nohup python test_bot.py &
© www.soinside.com 2019 - 2024. All rights reserved.