Keeeping the loop going until input (discord.py)

喜欢而已 提交于 2021-01-29 05:32:46

问题


I'm running a discord.py bot and I want to be able to send messages through the IDLE console. How can I do this without stopping the bot's other actions? I've checked out asyncio and found no way through. I'm looking for something like this:

async def some_command():
    #actions

if input is given to the console:
     #another action

I've already tried pygame with no results but I can also try any other suggestions with pygame.


回答1:


You can use aioconsole. You can then create a background task that asynchronously waits for input from console.

Example for async version:

from discord.ext import commands
import aioconsole

client = commands.Bot(command_prefix='!')


@client.command()
async def ping():
    await client.say('Pong')


async def background_task():
    await client.wait_until_ready()
    channel = client.get_channel('123456') # channel ID to send goes here
    while not client.is_closed:
        console_input = await aioconsole.ainput("Input to send to channel: ")
        await client.send_message(channel, console_input)

client.loop.create_task(background_task())
client.run('token')

Example for rewrite version:

from discord.ext import commands
import aioconsole

client = commands.Bot(command_prefix='!')


@client.command()
async def ping(ctx):
    await ctx.send('Pong')


async def background_task():
    await client.wait_until_ready()
    channel = client.get_channel(123456) # channel ID to send goes here
    while not client.is_closed():
        console_input = await aioconsole.ainput("Input to send to channel: ")
        await channel.send(console_input)

client.loop.create_task(background_task())
client.run('token')


来源:https://stackoverflow.com/questions/54494798/keeeping-the-loop-going-until-input-discord-py

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!