如何从外部Python文件调用已运行的Discord机器人函数并避免重启
跨脚本触发异步函数且不重启机器人的解决方案
问题说明
需要实现:运行xyz.py时,在已处于运行状态的bot.py的终端中打印"works"。
当前bot.py中的核心代码:
async def call_1(): print("works")
尝试直接在xyz.py中导入调用:
from bot import call_1 call_1()
但此操作会导致xyz.py重新启动bot.py中的机器人进程,无法达成预期效果。
原因分析
直接导入bot.py的代码时,Python会重新加载整个bot.py模块,包括其中机器人初始化、启动的逻辑,相当于启动了一个全新的机器人实例,而非和已运行的bot进程交互。因此必须通过进程间通信的方式实现跨脚本触发。
可行解决方案
方案1:本地Socket通信
通过本地Socket让xyz.py向运行中的bot.py发送触发指令,bot.py监听端口并执行对应函数。
修改bot.py,添加Socket服务并和机器人逻辑并行运行:
import asyncio # 替换为你实际使用的机器人库,比如discord.Client from your_bot_framework import Bot bot = Bot(your_bot_configs) async def call_1(): print("works") # 处理Socket客户端请求 async def handle_client(reader, writer): data = await reader.read(100) cmd = data.decode().strip() if cmd == "run_call1": await call_1() writer.close() await writer.wait_closed() # 启动本地Socket服务 async def start_socket_server(): server = await asyncio.start_server(handle_client, "127.0.0.1", 9000) async with server: await server.serve_forever() # 并行运行机器人和Socket服务 async def main(): await asyncio.gather( bot.start("your_bot_token"), start_socket_server() ) if __name__ == "__main__": asyncio.run(main())
xyz.py作为客户端发送触发指令:
import socket def trigger_call1(): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect(("127.0.0.1", 9000)) s.sendall(b"run_call1") if __name__ == "__main__": trigger_call1()
方案2:文件触发机制
让bot.py定时检查指定文件的存在性,xyz.py通过创建该文件触发函数执行。
修改bot.py,添加文件检查任务:
import asyncio import os from your_bot_framework import Bot bot = Bot(your_bot_configs) async def call_1(): print("works") # 定时检查触发文件 async def check_trigger(): trigger_path = ".trigger_call1" while True: if os.path.exists(trigger_path): await call_1() os.remove(trigger_path) await asyncio.sleep(0.5) # 检查间隔可调整 async def main(): await asyncio.gather( bot.start("your_bot_token"), check_trigger() ) if __name__ == "__main__": asyncio.run(main())
xyz.py创建触发文件:
def trigger_call1(): with open(".trigger_call1", "w") as f: f.write("") if __name__ == "__main__": trigger_call1()
内容的提问来源于stack exchange,提问作者Thribhuvan Rapolu
相关产品推荐
相关产品推荐

