Python编写Discord脚本多参数重复运行仅首次生效卡住求助
问题原因
os.system()是同步阻塞调用,会等待当前执行的子进程完全退出才会运行下一条命令,你的script.py启动后是永久运行的进程,不会主动退出,所以只会跑第一个账号的逻辑就卡住script.py里混用同步sleep()和异步协程逻辑,discord.py的异步事件循环会被同步sleep完全阻塞,所有事件都无法响应on_ready事件的异常处理逻辑错误,捕获到异常后再次调用client.run(),属于重复启动客户端,会直接卡死进程- 使用用户账号登录属于违反Discord服务条款的行为,账号有极高的被封禁风险,该操作不推荐
修复方案
1 重写main.py,改用多进程非阻塞启动子脚本
不要用os.system,改用subprocess.Popen后台启动子进程,不需要等待执行结束:
import os import csv import subprocess from time import sleep rows = [] with open('data.csv', 'r') as csvfile: csvreader = csv.reader(csvfile) for row in csvreader: rows.append(row) process_list = [] for _ in rows: # 构造参数列表,避免字符串拼接的空格转义问题 cmd = ["python3", "script.py"] + _ print(f"启动进程: {' '.join(cmd)}") # 后台启动子进程,不阻塞主流程 p = subprocess.Popen(cmd) process_list.append(p) sleep(10) # 等待所有子进程运行,保证主进程不退出 for p in process_list: p.wait()
2 修复script.py的逻辑错误
- 把同步
sleep换成异步的asyncio.sleep - 删掉异常处理里的
client.run调用,改成错误日志打印后跳过当前渠道 - 修正变量重名、重复导入、缺少intents声明等小问题
import time import os import sys import asyncio import discord import logging argumentList = sys.argv print(argumentList[1:]) TOKEN_AUTH = argumentList[1] os.environ['TZ'] = 'Asia/Kolkata' time.tzset() logging.basicConfig(handlers=[logging.FileHandler(filename="./discord.txt", encoding='utf-8', mode='a+')], format="%(asctime)s %(name)s:%(levelname)s:%(message)s", datefmt="%F %A %T", level=logging.INFO) client = discord.Client(intents=discord.Intents.default()) ids = argumentList[2:] sleep_time = 121 message_content = "enter your message" @client.event async def on_ready(): print(f"登录成功: {client.user}") while True: for channel_id in ids: try: channel1 = client.get_channel(int(channel_id)) if not channel1: logging.warning(f"找不到渠道: {channel_id}") continue await channel1.send(message_content) logging.info(f"发送消息成功到渠道: {channel_id}") print(f"发送完成,等待{sleep_time}分钟") # 用异步sleep不阻塞事件循环 await asyncio.sleep(sleep_time * 60) except Exception as e: logging.error(f"发送失败: {str(e)}") # 出错后等待1分钟再试下一个 await asyncio.sleep(60) continue client.run(TOKEN_AUTH, bot=False)
额外注意事项
- 运行多个账号时建议给每个账号配置独立的日志文件,避免日志写入冲突
- 不要设置过短的发送间隔,否则会触发Discord的反垃圾机制,直接封禁账号
- 再次提醒:使用用户账号自动化操作违反Discord的服务条款,可能导致账号永久封禁,建议改用官方机器人账号实现相关功能
内容的提问来源于stack exchange,提问作者Logwin Finserv
相关产品推荐
相关产品推荐

