Brendan Rodgers
Brendan Rodgers

Reputation: 305

Python - Contents of text file being posted as separate messages rather than one message using Discord.py bot

I am currently attempting to post the contents of a text file to a discord channel using Discord.py

The text file contents are below:

Competition English Premier League - Week 35 
Competitors Wolves v Everton 
Match Date Sunday, 12th  July 
Match Time ST: 12:00 
Channels: beIN Connect MENA 📺
   beIN Sports MENA 11 HD 
   beIN Sports MENA 2 HD 
   Belarus 5 Internet  
   Belarus 5 TV 

The structure of the text file above is how I am attempting to have the data from the text file outputted to discord.

Currently when I run my code (posted below) the information is correctly displayed but each line of the text file above is outputted as a separate discord message, but I require all of the content to be posted as one message.

Discordbot.py

import discord


client = discord.Client()


@client.event
async def on_member_join(member):
    for channel in member.guild.channels:
        if str(channel) == "general":
            await channel.send_message(f"""Welcome to the server {member.mention}""")



@client.event
async def on_message(message):
    if message.author == client.user:
        return
    
        
    if message.content == "!test":
        with open('/home/brendan/Desktop/finaltestng.txt', 'r') as file:
            data = file.readlines()
            for line in data:
                print(line)
                await message.channel.send(line)


client.run("*******")

I have attempted to change the code to this:

   if message.content == "!test":
        with open('/home/brendan/Desktop/finaltestng.txt', 'r') as file:
            data = file.readlines()
            await message.channel.send(data)

With the altered code I am able to receive the complete output as one message as required but the formatting is incorrect

['Competition English Premier League - Week 35 \n', 'Competitors Wolves v Everton \n', 'Match Date Sunday, 12th  July \n', 'Match Time ST: 12:00 \n', 'Channels: beIN Connect MENA :tv:\n', ' \xa0 beIN Sports MENA 11 HD \n', ' \xa0 beIN Sports MENA 2 HD \n', ' \xa0 Belarus 5 Internet  \n', ' \xa0 Belarus 5 TV \n', '\n']

From this point I am not sure what the best way forward would be.

Thank you in advance to anyone who is able to advise or provide a solution to this issue.

Upvotes: 1

Views: 480

Answers (1)

deadshot
deadshot

Reputation: 9061

The problem in your code you are sending each line in the file as new message instead what you can do is read the file once using file.read() and send it once.

Change this to

for line in data:
    print(line)
    await message.channel.send(line)

this

await message.channel.send(file.read().strip())

Upvotes: 1

Related Questions