discord.py 机器人的多个实例,具有多处理问题,实例不侦听事件



我正在制作一个discord.py片段,该片段应该有多个discord.py机器人实例。

机器人程序表示如下

class Bot(commands.Bot):
client = discord.Client()
def __init__(self, token):
intents = discord.Intents(messages=True, members=True, guilds=True)
self.client = commands.Bot(command_prefix="!", intents=intents)
self.token = token
print("Bot is starting...")
@client.event
async def on_ready(self):
print(f"{self.user} has connected to Discord!")
async def run(self):
print("Bot is running...")
try:
await self.run()
except Exception as e:
print(e)

但在控制台中,我只得到了3次Bot is starting...,因为我有3个代币

主引导程序代码类似于

def launch_bot(bot_instance: Bot):
asyncio.run(bot_instance.run())

async def main():
global global_bots_queue
global global_bots
pool = multiprocessing.Pool()
guild_name = input('Enter the desired guild name: ')
global_bots_queue = retrieve_tokens()
for token in global_bots_queue:
global_bots[token] = Bot(token)
for token in global_bots_queue:
pool.apply_async(launch_bot, args=(global_bots[token],))
pool.close()
pool.join()

if __name__ == '__main__':
event_loop = asyncio.get_event_loop()
event_loop.run_until_complete(main())

请问,我应该编辑什么才能使这个代码正常工作?

输出:

Bot is starting...
Bot is starting...
Bot is starting...
Process finished with exit code 0

您使用的多处理系统被搞砸了,所以我对它做了一些更改,并测试它现在可以工作了

class Bot(commands.Bot):
def __init__(self, token):
intents = discord.Intents(messages=True, members=True, guilds=True)
super().__init__(command_prefix="!", description="A bot for the Discord server", intents=intents)
self.token = token
print("Bot is starting...")

async def on_ready(self):
print(f"Bot has connected to Discord!")

def run_(self):
print("Bot is running...")
try:
self.run(self.token)
except Exception as e:
print(e)

def main():
global global_bots_queue
global global_bots
global_bots_queue = retrieve_tokens()
# for token in global_bots_queue:
#     global_bots[token] = Bot(token)
proccess = []
global_bots = []
for token in global_bots_queue:
proccess.append(Process(target=Bot(token).run_, args=()))
global_bots.append(Bot(token))
for p in proccess:
p.start()
for p in proccess:
p.join()

if __name__ == '__main__':
main()

最新更新