python discord.py 的 discord 机器人的单一动作脚本

Single action script for discord bot with python discord.py

我知道 discord 机器人通常处于监听(阻塞)循环中,但是我如何创建一个函数来连接、发送消息或执行任何操作并在非阻塞流中断开连接?

我正在使用 discord.py,我正在寻找类似的东西:

import discord

TOKEN = "mYtOkEn"
    
discord.connect(TOKEN)
discord.send("I'm sending this message")
discord.disconnect()

我已经尝试过使用异步但线程有问题,所以想知道是否有更简单的方法。

这是一个按钮,当点击时,执行该操作,但之后它可以继续处理其他任务

预先致谢

实现此目的的一种方法是使用自定义事件循环。 示例:

import discord
import asyncio
from threading import Thread

TOKEN = "secret"

client = discord.Client()


def init():
    loop = asyncio.get_event_loop()
    loop.create_task(client.start(TOKEN))
    Thread(target=loop.run_forever).start()


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

    await message.channel.send('Hello!')


@client.event
async def on_ready():
    print("Discord bot logged in as: %s, %s" % (client.user.name, client.user.id))

init()
print("Non-blocking")

查看此内容以获取更多信息:

感谢您的帮助和支持。通过 SleepyStew 的回答,我找到了解决问题的途径,并采用了这种方式:

import discord
import asyncio

def discord_single_task():

    # Define Coroutine
    async def coroutine_to_run():
        TOKEN = "Secret"

        # Instantiate the Client Class
        client = discord.Client()

        # # Start (We won't use connect because we don't want to open a websocket, it will start a blocking loop and it is what we are avoiding)
        await client.login(TOKEN)
                
        # Do what you have to do
        print("We are doing what we want to do")

        # Close
        await client.close()

    # Create Loop to run coroutine
    loop = asyncio.new_event_loop()
    llll = loop.create_task(coroutine_to_run())
    loop.run_until_complete(llll)

    return 'Action performed successfully without a blocking loop!'