使用python编写不和bot的单动作脚本



我知道通常不和谐机器人是在一个监听(阻塞)循环,但我怎么能创建一个功能,连接,发送消息或执行任何动作和断开在一个非阻塞流?

我正在使用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")
C-Python asyncio: running discord.py in a thread

感谢您的帮助和支持。有了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!'

最新更新