首页 > 解决方案 > 不和谐机器人。bot.loop.create_task(background_task()) 不起作用

问题描述

我有这个代码:

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())不起作用。我该怎么办?我会很感激你的帮助。

标签: pythondiscorddiscord.py

解决方案


而真正解决我的问题

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)

推荐阅读