Skip to content
Advertisement

Reading a text file and splitting into separate words in python3.8, using discord.py

I’m trying to make a discord bot using python 3.8 and discord.py in pycharm. The bot’s function is to read a text file and write out each word as a separate message and send it into a discord server. Now I have the text file and it can print out the words but it can’t do it separately.

Below is the relevant code:

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

I read some other answers where they stated that f.readlines()would resolve the issue but that left it sending only one line of text. I tried

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

and then trying to call the function with await channel.send(script_message()) but that leaves me with errors where it’s asking me to correct the syntax. So how can I send the contents of the text file as separate messages?

Advertisement

Answer

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)

And in your on_message event

elif message.content.startswith('r!start'):
    await message.channel.send('Starting Story...')
    await script_message(message.channel)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement