【问题标题】:Discord Bot sends text file line by lineDiscord Bot 逐行发送文本文件
【发布时间】:2020-08-21 09:19:06
【问题描述】:

我正在处理一个不和谐的命令,它将整个文本文件逐行写入聊天,我尝试制作它,但不知何故它不能正常工作。

    file = open('story.txt', 'r')

    @client.command(alisases = ['readfile'])
     async def story(ctx):
        for x in file:
            await ctx.send(file)

它运行,但只写这些行:

<_io.textiowrapper name="story.txt" mode="r" encoding="cp1250">

【问题讨论】:

  • 您正在发送文件对象的字符串表示形式。你的意思是ctx.send(x)

标签: python discord discord.py


【解决方案1】:

您发送的是文件对象的字符串表示,而不是其中的行。

你可以这样做:

@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)

此外,使用with open 语法是一个很好的做法,因为它可以确保正确关闭文件。

【讨论】:

  • 如果你不介意的话,我还有一个问题。我该如何计时这些消息?因为它写得太快了。
  • 您可以在每次迭代结束时添加time.sleep(&lt;amount of seconds&gt;)
  • 不要使用time.sleep,它会阻塞(不适用于async)。请改用await asyncio.sleep
  • @Benjin:我同意你的看法。
  • @y_os:在await ctx.send(line) 之后,您可以添加另一行,例如await asyncio.sleep(seconds)。 PS:别忘了导入 asyncio :D
猜你喜欢
  • 2021-08-10
  • 2021-04-05
  • 1970-01-01
  • 2018-11-24
  • 2019-02-22
  • 2012-12-07
  • 2020-08-18
  • 2021-08-05
  • 2019-01-06
相关资源
最近更新 更多