繁体   English   中英

如何在另一个进程/线程中运行模块并使用它的功能而不阻塞主脚本

[英]How do I run a module in another process/thread and use it's functions without blocking main script

我试图能够发送/编辑/删除消息以及 webhook 不能做的所有事情(我不想在这种特定情况下使用它们)。 我还想看看如何导入其他一些模块,这些模块就像在我调用run function 时自身循环并阻止整个脚本一样。 我不知道如何在多进程或线程中运行它。 我的意思是是的,我可以通过run function 启动一个进程或线程。 但是之后我应该如何调用send_msg function 呢? (或edit_msgdelete_msg ,我没有在这里写它们,因为它会很相似)

bot.py:

import discord

def run(token):
    
    client = discord.Client()

    @client.event
    async def on_ready():
        print("Bot is ready.")

    @client.event
    async def on_message(message):
        if message.author == client.user:
            return

        return #for now just trying to get the bot to send anything with the send_msg function from another process.

    client.run(token)


def send_msg(client, channel_id, text):
    channel = client.get_channel(channel_id)
    if channel is None: return None
    
    try:
        msg = await channel.send(text)
    except Exception as e:
        print("Could not send:", repr(e))
        return None
    else:
        return msg

我希望能够像这样使用它:

  1. 将此 bot.py 导入主脚本
  2. 从主脚本run function 启动多进程/线程
  3. 当我有消息要发送时,从主脚本调用send_msg (编辑和删除是相似的,所以我只需要了解这一点)
  4. send_msg获取返回值到主脚本中并在主脚本中继续我的方式,而不会被机器人或任何东西阻止(在主脚本中发送/编辑/删除时必须等待是可以的,但我不想被阻止由机器人的异步循环永远)

那么有没有办法对整个模块进行多进程/线程处理? 或者有解决办法吗? 或者我应该以某种方式自己发出 POST 请求,而不是使用 discord.py (但我不知道如何因为网关)?

对于您的问题,我没有确切的解决方案,但我会先将其放入一个 class 中。 在这一点上,我没有看到您在“send_msg”function 中使用您在“运行”function 中声明的相同客户端。 还记得在定义“send_msg”方法之前添加异步。

import discord


def DiscordBot():
    def __init__(self, client):
        self.client = discord.Client()

    def run(token):

        @self.client.event
        async def on_ready():
            print("Bot is ready.")

        @self.client.event
        async def on_message(message):
            if message.author == self.client.user:
                return

            return #for now just trying to get the bot to send anything with the send_msg function from another process.

        self.client.run(token)


    async def send_msg(self, channel_id, text):
        channel = self.client.get_channel(channel_id)
        if channel is None: return None
        
        try:
            msg = await channel.send(text)
        except Exception as e:
            print("Could not send:", repr(e))
            return None
        else:
            return msg

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM