python - 不和谐机器人。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())不起作用。我该怎么办?我会很感激你的帮助。
解决方案
而真正解决我的问题
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)
推荐阅读
- ruby - 如何通过在 rails 5 restful json api 中传递用户 authentication_token 来显示用户对象数据?
- qt - 如何实现地理参考 MapQuickItem
- php - 如何安装 laravel/dusk?
- python - 用于取消正在运行的 Oracle SQL 查询的 Python 代码
- laravel-5 - 为什么将 ID 替换为另一个表中的值?Laravel 属于
- javascript - 如何在 Nestjs 中刷新令牌
- php - 模板未从控制器 drupal 8 呈现
- jquery - 切换内容可编辑属性
- php - SVN Tortoise 使用 PHP 更新
- python - Keras:使用更大的训练集更新模型