【问题标题】:Discord.py: How to send a message without using async and awaitDiscord.py:如何在不使用 async 和 await 的情况下发送消息
【发布时间】:2022-08-06 03:49:28
【问题描述】:

如何创建一个函数(没有异步),每次它(函数)在代码中的某处执行时向特定通道发送消息?

def sendMsg():
    channel = client.getChannel(Channel id)
    message.channel.send(\"example message\")
    #excecuting the function
    sendMsg()

什么都不做

async def on_message():
    await message.channel.send(\"example message\")

只有这个有效

所以我的问题是我是否可以修改顶部的代码使其工作?

  • 请包括minimal reproducible example。不使用 asyncio 就无法通过 discordpy 发送消息。你能得到的最接近的是上课。您可能需要阅读 asyncio 的文档。
  • 你说的那个“有效”不工作. await 是必需的。
  • @EricJin 抱歉,在我的工作代码中,我使用了等待。只是忘了写在例子里
  • 你需要async def send_msg,然后你可以在它前面使用await message.channel.sendmessage 也没有在其中定义 - 你的意思是让它成为一个全局变量还是作为参数传递?
  • >还没有定义消息。好吧,idk,但它有效

标签: python async-await discord discord.py


【解决方案1】:

如果您需要在异步上下文之外发送消息,则需要将任务添加到事件循环中。请注意,当您“调用”协程时,您会得到实际的协程对象。 “调用”它实际上并没有运行协程,您需要将它放在事件循环中才能运行。

asyncio.get_event_loop().create_task(<coro>)

# use it like this
asyncio.get_event_loop().create_task(ctx.send('test'))
asyncio.get_event_loop().create_task(message.channel.send("example message"))

【讨论】:

    【解决方案2】:

    确实需要异步来同步消息

    如果您想将其作为 selfbot 响应消息,请执行

    # Import's here
    from discord.ext import commands
    
    bot = commands.Bot(command_prefix='!', help_command=None, self_bot=True)
    
    @bot.event
    async def on_message(message):
        if message.content.startswith("Hello"):
           await message.channel.send(f"Hi @{message.author}")
    
    
    bot.run('token ofc', bot=False)
    

    无论如何,如果你想用机器人来做这个,请删除 self_bot=Truebot=False

    【讨论】:

      【解决方案3】:

      埃里克的回答是正确的。此外,为了从discord.py中获取循环事件,可以使用client.loop获取discord.py的asyncio eventloop

      也就是说,使用asyncio.run_coroutine_threadsafe(def,loop) 安全地将任务提交到 event_loop

      client = discord.Client()
      async def send_message_to_specific_channel(message='abc',id=123):
        channel = client.get_channel(id)
        await channel.send(message)
      asyncio.run_coroutine_threadsafe(send_message_to_specific_channel('abc',123),client.loop)
      
      

      【讨论】:

        猜你喜欢
        • 2018-09-24
        • 2020-11-08
        • 1970-01-01
        • 2019-12-04
        • 2020-12-29
        • 1970-01-01
        • 2018-12-04
        • 2022-11-15
        • 2019-10-24
        相关资源
        最近更新 更多