Skip to content
Advertisement

Discord.py Stuck Trying to Loop Through Logs and Send to Server

I am trying to create a simple discord bot that parses a log file that is constantly being written to and sending the new lines to a discord channel I have on my server name logs.

Parsing the file and printing the output is easy and works just fine. My problem is trying to incorporate it into discord. It seems my program is hanging sometime after connecting and never sends any messages. The bot makes it on the server and completes the on_ready.

I’m brand new to discord.py so I’d appreciate any guidance. Thank you.

import time, discord, asyncio, nest_asyncio

nest_asyncio.apply()

TOKEN = '123'

class MyClient(discord.Client):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    async def on_ready(self):
        print('Logged in as')
        print(self.user.name)
        print(self.user.id)
        print('------')

        self.bg_task = self.loop.create_task(self.background_task())

    async def background_task(self):
        channel = discord.utils.get(ctx.guild.channels, name="logs")
        with open('log.txt', 'r') as f:
            while True:
                line = ''
                while len(line) == 0 or line[-1] != 'n':
                    tail = f.readline()
                    if tail == '':
                        time.sleep(0.1)
                        continue
                    line += tail
                    print(f"Sending: {line}")
                    await channel.send(line)
                    await asyncio.sleep(1)

client = MyClient()
client.run(TOKEN)

Advertisement

Answer

I’m also working on a discord bot with discord.py, so I think I can help you. Here’s how I would do it:

When, the bot is ready, it prints out that he’s logged in

import discord
client = discord.Client()

@client.event
async def on_ready():
    print('Logged in as ' + str(client.user))

When you want to see whats inside the .txt file, you just have to enter ‘show content’

@client.event
async def on_message(message):
    if message.content == 'show content':

        line = ' '

        while len(line) != 0:

First it reads the uppermost line

            f = open('C:\Users\USERNAME\FOLDER\logs.txt', 'r')
            line = f.readline()
            content_of_textfile = f.read()
            f.close()

And then deletes it from the file. I know this isn’t the cleanest way and I’m sure there’s a much better solution

            f = open('C:\Users\USERNAME\FOLDER\logs.txt', 'w')
            content_of_textfile.replace('line', '')
            f.write(content_of_textfile)
            f.close()

Then it’s send the message to your discord channel

            await message.channel.send(line)

client.run('YOUR TOKEN')

Hope this helps :D

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement