【发布时间】:2022-01-19 11:38:20
【问题描述】:
我试图制作一个类似于 Minecraft 服务器控制台的不和谐机器人,但是,我觉得这是一个非常基本的问题,我希望机器人继续发送 Minecraft 服务器的输出并通过消息写入输入一个特定的通道,但当然,如果你有一个循环运行程序的其余部分没有运行,我尝试了多进程和多线程,但由于异步函数它没有工作。 这是我的代码:
minecraft_dir = r"C:\Users\Pablo\Desktop\1.18 server - Copy"
executable = r'java -Xms4G -Xmx4G -jar "C:\Users\Pablo\Desktop\1.18 server - Copy\server.jar" java'
process = None
async def start_serv(msg):
os.chdir(minecraft_dir)
process = subprocess.Popen(executable,stdin=PIPE,stdout=PIPE, text=True)
for line in process.stdout:
await msg.channel.send(line)
def serv_cmd(cmd):
if cmd == "stop":
process = None
cmd = cmd + "\n"
cmd = cmd.encode()
process.stdin.write(cmd)
process.stding.flush()
@client.event
async def on_message(message):
global process
if message.author.id != client.user.id and message.channel.name == "mc-server-console":
command = message.content
command=command.lower()
if command == "start":
if process == None:
await message.channel.send("yessir")
if process != None:
serv_cmd(command)
这是我的多线程尝试:
async def start_serv():
os.chdir(minecraft_dir)
process = subprocess.Popen(executable,stdin=PIPE,stdout=PIPE, text=True)
for line in process.stdout:
await channel.send(line)
time.sleep(0.1)
def serv_cmd(cmd):
if cmd == "stop":
process = None
cmd = cmd + "\n"
cmd = cmd.encode()
process.stdin.write(cmd)
process.stding.flush()
def main():
@client.event
async def on_message(message):
global process
if message.author.id != client.user.id and message.channel.name == "mc-server-console":
command = message.content
command=command.lower()
if command == "start":
if process == None:
await message.channel.send("yessir")
thread2.start()
if process != None:
serv_cmd(command)
thread1 = threading.Thread(target=main)
thread1.start()
thread2 = threading.Thread(target=start_serv)
如果有人知道只在服务器输出更新时发送消息的方法,我认为这也可以。
【问题讨论】:
-
你能展示你在多处理和多线程方面的尝试吗?
-
@jakub 你去我找不到我的多处理尝试,但我不认为它有很大不同。
-
为此,您只需在每次运行脚本时更新您的机器人。您还可以创建一个 cog 来执行此操作,它不应停止任何其他脚本。
-
@EpicEfeathers 我将如何更新脚本?
-
老实说,我只是创建一个 cog 并在其中放置您的循环,因为它不会影响您的其他文件。
标签: python discord.py stdout minecraft