gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:47:24 26 4
gpt4 key购买 nike

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

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

最佳答案

每次发送之前,您必须更改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

关于python - 如何在循环中打印列表中的不同值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51120748/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com