python - 如何在循环中从列表中打印不同的值?
问题描述
我正在尝试制作一个 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
推荐阅读
- c# - 如何匹配第一次出现的字符并将其拆分
- aws-iot - AWS androidIoT:KEYSTORE_PATH 位置
- ios - iOS Swift 如何在后台播放 AudioServicesPlaySystemSound 或 AudioServicesPlayAlertSound
- react-native - React Native 中使用的 Webview 中的“无效 CORS 请求”错误
- javascript - 谁在 Web 浏览器中实际执行 HTTP 请求?
- haskell - Haskell:等效的数组循环比较
- spring - 如何在基于 Spring 的反应式应用程序中从身份验证中排除路径?
- php - 执行命令在 sql server 中不起作用
- selenium - GMail - 等待页面完全加载
- r - ggplot2 中的轴标签被截断或覆盖图形