将客服机器人加入到群聊中后,可以让机器人定时禁言群里面的所有普通成员,一段时间后重新恢复发言,这样能很好的管理成员提出的问题,避免在非正常时间段内提问。
这里用到了 TG 的两个机器人:
- @BotFather 创建机器人(API_TOKEN)
- @getidsbot 输出你的用户ID(chat_id)或者群ID(group_id)
配置脚本
创建目录并将脚本放进去
mkdir -p /opt/tg_bot
cp nightmute_bot.py /opt/tg_bot/
chmod +x /opt/tg_bot/nightmute_bot.py
cat nightmute_bot.py
import logging
import datetime
from telegram import ChatPermissions, Update
from telegram.ext import (
ApplicationBuilder, CommandHandler, ContextTypes
)
from backports.zoneinfo import ZoneInfo
BOT_TOKEN = "Your_API_TOKEN"
GROUP_ID = -100xxx
logging.basicConfig(level=logging.INFO)
async def mute_group(context: ContextTypes.DEFAULT_TYPE):
await context.bot.set_chat_permissions(
chat_id=GROUP_ID,
permissions=ChatPermissions(can_send_messages=False)
)
await context.bot.send_message(
chat_id=GROUP_ID,
text="🌙 夜间模式已开启!\n\n我要睡到明早七点,今天又收获了不少呢,祝好梦 😴"
)
logging.info("夜间模式已开启")
async def unmute_group(context: ContextTypes.DEFAULT_TYPE):
await context.bot.set_chat_permissions(
chat_id=GROUP_ID,
permissions=ChatPermissions(can_send_messages=True)
)
await context.bot.send_message(
chat_id=GROUP_ID,
text="☀ 夜间模式结束啦!\n\n今天又是元气满满的一天,加油 😉"
)
logging.info("夜间模式结束")
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("Bot 已启动")
async def post_init(app):
tz = ZoneInfo("Asia/Shanghai")
app.job_queue.run_daily(mute_group, time=datetime.time(hour=22, minute=0, tzinfo=tz))
app.job_queue.run_daily(unmute_group, time=datetime.time(hour=7, minute=0, tzinfo=tz))
logging.info("定时任务已设置")
def main():
app = ApplicationBuilder().token(BOT_TOKEN).post_init(post_init).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("mute", mute_group))
app.add_handler(CommandHandler("unmute", unmute_group))
logging.info("Bot 正在运行...")
app.run_polling() # <== 这是阻塞式同步调用,不需要 asyncio.run
if __name__ == "__main__":
main()
配置脚本运行环境
创建 Python 虚拟环境
apt install -y python3 python3-pip python3-venv
cd /opt/tg_bot
python3 -m venv venv
source venv/bin/activate
pip install python-telegram-bot==20.7
pip install python-telegram-bot[job-queue]
deactivate
注册成 systemd 服务
nano /etc/systemd/system/telegram-nightmute.service
[Unit]
Description=Telegram Group Night Mute Bot
After=network.target
[Service]
Type=simple
WorkingDirectory=/opt/tg_bot
ExecStart=/opt/tg_bot/venv/bin/python3 /opt/tg_bot/nightmute_bot.py
Restart=on-failure
RestartSec=10
StartLimitIntervalSec=60
StartLimitBurst=3
User=root
Environment=PYTHONUNBUFFERED=1
[Install]
WantedBy=multi-user.target
首次启动服务
systemctl daemon-reexec
systemctl daemon-reload
systemctl enable telegram-nightmute.service
systemctl start telegram-nightmute.service
重启服务
systemctl restart telegram-nightmute.service
查看日志输出
journalctl -u telegram-nightmute.service -f
评论区