Bot stops working after few minutes without showing errors

I have a bot that monitors a text file for new entries and sends messages when updates occur. The problem is that it works fine for about 4-5 minutes, then suddenly stops responding without any error messages showing up.

The text file gets new data added randomly from an external source. When new lines are added, the bot should detect this and post a message, but it just dies silently after a short while. I think it might be a memory issue but I’m not sure.

import discord
import asyncio
from discord.ext import commands
import time

global line_number

client = commands.Bot(command_prefix="$")

def fetch_latest(): # Gets the newest entry from the file
    global newest
    global file_data
    file_data = open('updates.txt','r')
    entries = file_data.readlines()
    file_data.close()
    newest = entries[len(entries)-1]

def count_lines(): # Gets total number of lines in file
    global line_number
    f = open("updates.txt", 'r')
    lines = f.readlines()
    f.close()
    line_number = 0

    for entry in lines:
        line_number += 1
    f.close()
    return line_number

async def monitor(): # monitors for file changes and posts updates
    global line_number

    current = count_lines()
    previous = current
    await client.wait_until_ready()

    while True:
        if current != previous:
            previous = current
            fetch_latest()
            message = "Alert: " + newest
            await client.send_message(discord.Object('******'),message)
            previous = current
        else:
            current = count_lines()

client.loop.create_task(monitor())        
client.run('***********')

Your bot’s dying silently because exceptions are getting swallowed by the async event loop. I ran into the same thing building a file monitor for game server logs - unhandled exceptions in background tasks just disappear without a trace.

Your code has a few problems causing this. That double f.close() call will throw an exception after the first loop, and without try-except blocks in your async task, the bot just dies quietly. Wrap your monitor function in try-except and log the exceptions so you can see what’s breaking.

Also, that tight while loop without any sleep is eating all your resources. I learned this the hard way when my monitoring bot killed an entire VPS - it was polling files thousands of times per second. Add await asyncio.sleep() so your loop actually yields control back to the event system.

Your while loop runs nonstop without any delay, which eventually crashes the event loop. I hit this same issue building a log monitoring bot last year. The problem is your infinite loop in monitor() never gives control back to asyncio. Just add await asyncio.sleep(1) at the end of your while loop to fix the resource hogging. Also spotted you’re using deprecated send_message() - that got removed in newer discord.py versions, which explains why it’s failing silently. Switch to channel objects and use channel.send() instead. Your file handling creates unnecessary overhead too. Opening and closing files repeatedly can cause file locks or permission issues depending on your OS. Try the watchdog library for proper file monitoring - it’s event-driven instead of polling-based and way more efficient.

I see the problem. Your loop’s running without breaks and those file operations are making a mess. File monitoring with Discord bots is always problematic though.

I dealt with this exact thing monitoring server logs at work. Started with Python, kept hitting the same silent failures and resource issues you’re seeing. The async loops would randomly die, especially under load.

Ditched that approach and switched to Latenode. Their file watcher triggers handle monitoring automatically. When your text file updates, it fires instantly - no polling loops needed.

Just connect the file trigger to a Discord webhook node, format your message, done. No async headaches, memory leaks, or silent crashes. I’ve run file monitoring workflows for months without a single failure.

Way cleaner than debugging Python async code and cleaning up file handles. Plus you get proper error handling and logging built in.

Your bot’s stuck because you’re missing await asyncio.sleep() in that while loop. Without it, the loop runs nonstop and blocks everything.

You’re also opening/closing files repeatedly which will cause problems. And calling f.close() twice in count_lines() throws an error.

Honestly though, monitoring files this way is pretty fragile. I dealt with something similar last year - needed to watch multiple log files and trigger different actions.

Instead of fixing all the Python issues, I switched to Latenode. Their file monitoring triggers actually work, and you can hook them straight to Discord webhooks or whatever service you need.

Super simple workflow - file changes trigger automatically, process the content, format your message, send it wherever. No infinite loops, memory leaks, or silent failures.

I’ve been running similar setups for months without any downtime. Way more reliable than debugging async Python code.

Your global variables are getting corrupted when file operations fail - that’s why it’s failing silently. I had the same issue with a bot monitoring CSV exports from a trading system. The file was locked by the external process writing to it, so reads would fail without throwing obvious errors. Your current variable never updates in the main loop, so you’re stuck comparing the same values forever. Move current = count_lines() to the top of your while loop. Also, send_message() was deprecated years ago and throws exceptions in newer discord.py versions. But the bigger problem is file locking. When your external source writes to the file, it temporarily locks it, causing silent read failures. I fixed this by copying the target file to a temp location first, then reading from that copy to avoid conflicts with the writer process.

classic mistake - you’re calling f.close() twice in count_lines, so it throws an exception after the first one. that infinite while loop with no sleep will also eat your CPU and eventually crash the bot. i’ve made this same mistake with file watchers before - they always fail silently like this.