【问题标题】:Reading a text file and splitting into separate words in python3.8, using discord.py在python3.8中读取文本文件并拆分成单独的单词,使用discord.py
【发布时间】:2020-11-30 01:36:58
【问题描述】:

我正在尝试在 pycharm 中使用 python 3.8 和 discord.py 制作一个不和谐的机器人。该机器人的功能是读取文本文件并将每个单词写成单独的消息并将其发送到不和谐服务器。现在我有了文本文件,它可以打印出单词,但不能单独打印。

下面是相关代码:

f = open("test.py")

@client.event
async def on_message(message):
    if message.content.startswith('r!help'):
        channel = message.channel
        await channel.send('Help')
    elif message.content.startswith('r!start'):
        channel = message.channel
        await channel.send('Starting Story...')
        await channel.send(f.readlines())

我阅读了一些其他答案,他们说f.readlines() 可以解决问题,但它只发送一行文本。我试过了

def script_message():
with open('words.txt','r') as f:
    for line in f:
        for word in line.split():
           print(word)    

然后尝试使用await channel.send(script_message()) 调用该函数,但这给我留下了要求我更正语法的错误。那么如何将文本文件的内容作为单独的消息发送呢?

【问题讨论】:

  • for line in f: await channel.send(line) 显然是这方面的尝试。你试过了吗?

标签: python discord.py discord.py-rewrite


【解决方案1】:
async def script_message(channel):
    with open("words.txt") as f:
        data = f.readlines()
    for i in data:
        for j in i.split(" "):
            await channel.send(j)

在您的on_message 活动中

elif message.content.startswith('r!start'):
    await message.channel.send('Starting Story...')
    await script_message(message.channel)

【讨论】:

    猜你喜欢
    • 2013-05-31
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    相关资源
    最近更新 更多