Python Discord Bot逐行发送文本文件
我正在使用discord命令,它将整个文本文件逐行写入聊天室,我尝试使用它,但不知为什么它不能正常工作Python Discord Bot逐行发送文本文件,python,discord,discord.py,Python,Discord,Discord.py,我正在使用discord命令,它将整个文本文件逐行写入聊天室,我尝试使用它,但不知为什么它不能正常工作 file = open('story.txt', 'r') @client.command(alisases = ['readfile']) async def story(ctx): for x in file: await ctx.send(file) 它运行,但只写入以下行: 您发送的是文件对象的字符串表示,而不是其
file = open('story.txt', 'r')
@client.command(alisases = ['readfile'])
async def story(ctx):
for x in file:
await ctx.send(file)
它运行,但只写入以下行:
您发送的是文件对象的字符串表示,而不是其中的行 你可以这样做:
@client.command(alisases = ['readfile'])
async def story(ctx):
with open('story.txt', 'r') as story_file:
for line in story_file:
await ctx.send(line)
另外,最好使用带有open语法的
,因为它可以确保文件正确关闭 您发送的是文件对象的字符串表示形式,而不是其中的行
你可以这样做:
@client.command(alisases = ['readfile'])
async def story(ctx):
with open('story.txt', 'r') as story_file:
for line in story_file:
await ctx.send(line)
另外,最好使用带有open
语法的,因为它可以确保文件正确关闭 您正在发送文件对象的字符串表示形式。您的意思是ctx.send(x)
?您正在发送文件对象的字符串表示形式。你是说ctx.send(x)
?如果你不介意的话,我还有一个问题。我如何计算这些信息的时间?因为它写得太快了。你可以在每次迭代结束时添加一个time.sleep()
,不要使用time.sleep
,它会阻塞(不适合async
)。使用wait asyncio.sleep
instead@Benjin:我同意你的看法。@y\u os:wait ctx.send(line)
之后,你可以添加另一行,如wait asyncio.sleep(seconds)
。别忘了导入asyncio:dal,如果你不介意的话,我还有一个问题。我如何计算这些信息的时间?因为它写得太快了。你可以在每次迭代结束时添加一个time.sleep()
,不要使用time.sleep
,它会阻塞(不适合async
)。使用wait asyncio.sleep
instead@Benjin:我同意你的看法。@y\u os:wait ctx.send(line)之后,你可以添加另一行,如wait asyncio.sleep(seconds)
。别忘了导入asyncio:D