如何在循环中从列表中打印不同的值?

时间:2018-07-01 05:48:57

标签: python python-3.x

我正在尝试制作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')

问题在于,机器人会随机选择一个图像,然后一遍又一遍地继续发布相同的图像。如何强制发布图片在每个循环中都不同?

1 个答案:

答案 0 :(得分:2)

每次发送之前,您必须更改postimage的值。

async def my_background_task():
    await client.wait_until_ready()
    channel = discord.Object(id='channel_id_here')
    while not client.is_closed:
        postimage = random.choice(list(open('imgdb.txt'))) # Open my list of urls and then pick one from there.
        await client.send_message(channel, postimage)
        await asyncio.sleep(10) # Run every 10 seconds for testing