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:
JavaScript
x
13
13
1
f = open("test.py")
2
3
@client.event
4
async def on_message(message):
5
if message.content.startswith('r!help'):
6
channel = message.channel
7
await channel.send('Help')
8
elif message.content.startswith('r!start'):
9
channel = message.channel
10
await channel.send('Starting Story...')
11
await channel.send(f.readlines())
12
13
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
JavaScript
1
6
1
def script_message():
2
with open('words.txt','r') as f:
3
for line in f:
4
for word in line.split():
5
print(word)
6
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
JavaScript
1
7
1
async def script_message(channel):
2
with open("words.txt") as f:
3
data = f.readlines()
4
for i in data:
5
for j in i.split(" "):
6
await channel.send(j)
7
And in your on_message
event
JavaScript
1
4
1
elif message.content.startswith('r!start'):
2
await message.channel.send('Starting Story...')
3
await script_message(message.channel)
4