首页 > 解决方案 > 如何在循环中从列表中打印不同的值?

问题描述

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

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

标签: pythonpython-3.x

解决方案


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

推荐阅读