不和谐的机器人。 bot.loop.create_task(background_task())不起作用

时间:2020-10-30 07:14:48

标签: python discord discord.py

我有此代码:

import asyncio
import random

from discord.ext import commands

bot = commands.Bot(command_prefix='.')

a=['Hello','Hi','Hello World']

async def background_task():
    time = 5 # 86400
    await asyncio.sleep(time)
    w = random.choice(a)
    q = "".join(w)
    message = q
    await bot.get_channel(id_channel).send(message)

async def on_ready():
    print('Bot logged as {}'.format(bot.user))


async def on_message(ctx):
    pass

bot.loop.create_task(background_task())
token = 'token'
bot.run(token)

我需要循环 background_task()。但是 bot.loop.create_task(background_task())无法正常工作。我该怎么办?感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

True解决我的问题

import asyncio
import random

from discord.ext import commands

bot = commands.Bot(command_prefix='.')

a=['Hello','Hi','Hello World']


async def background_task():
    w = random.choice(a)
    q = "".join(w)
    message = q
    while True:
        time = 5 # 86400
        await asyncio.sleep(time)
        await bot.get_channel(771365589355855883).send(message)

async def on_ready():
    print('Bot logged as {}'.format(bot.user))


async def on_message(ctx):
    pass

bot.loop.create_task(background_task())
token = 'NzcxMzYwMzk4NzAzOTg0NjYx.X5q_Wg.w00I702euybW-Z2AYSQpHIsfifQ'
bot.run(token)