我试图制造一个Discord机器人,而我想添加的功能之一是从列表中选择一个随机项目并将其发布。一段时间后,从同一列表中选择一个新项目并发布。
该Discord.py github上有做循环/后台任务的例子。
import discord
import asyncio
client = discord.Client()
async def my_background_task():
await client.wait_until_ready()
counter = 0
channel = discord.Object(id='channel_id_here')
while not client.is_closed:
counter += 1
await client.send_message(channel, counter)
await asyncio.sleep(60) # task runs every 60 seconds
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
client.loop.create_task(my_background_task())
client.run('token')
上面的代码工作正常。僵尸程序会不断记录日志。这是我尝试更改它的方法。
import discord
import asyncio
import random
client = discord.Client()
async def my_background_task():
await client.wait_until_ready()
postimage = random.choice(list(open('imgdb.txt'))) #Opens my list of urls and then pick one from there.
channel = discord.Object(id='channel_id_here')
while not client.is_closed:
await client.send_message(channel, postimage)
await asyncio.sleep(10) # task runs every 10 seconds for testing
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
client.loop.create_task(my_background_task())
client.run('token')
问题是,机器人会随机选择一个图像,然后一遍又一遍地继续发布相同的图像。如何强制发布图片在每个循环中都不同?
相关分类