Python Discord bot unexpectedly stops responding

I’m having trouble with my Discord bot running on a friend’s Raspberry Pi VPS. It starts fine and responds to commands for about 5 minutes, but then it stops working properly. When I click the green button, I get an “Interaction Failed” message. If I try the command again, it works and remembers the user ID in the sign-in dictionary. But after another 5 minutes, the same issue happens.

The bot doesn’t seem to completely stop, but something’s not right. Could this be a code issue or a VPS problem? Here’s a simplified version of my code:

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='!')

user_data = {}

@bot.command()
async def register(ctx):
    button = discord.ui.Button(label='Sign Up', style=discord.ButtonStyle.green)
    
    async def button_click(interaction):
        if interaction.user.id in user_data:
            await interaction.response.send_message('Already registered', ephemeral=True)
            return
        
        await interaction.response.send_modal(RegistrationForm())

    button.callback = button_click
    view = discord.ui.View()
    view.add_item(button)
    await ctx.send('Click to register', view=view)

class RegistrationForm(discord.ui.Modal):
    def __init__(self):
        super().__init__(title='Registration Form')
        self.username = discord.ui.TextInput(label='Username')
        self.add_item(self.username)

    async def on_submit(self, interaction):
        user_data[interaction.user.id] = {'username': self.username.value}
        await interaction.response.send_message('Registration complete!', ephemeral=True)

bot.run('YOUR_TOKEN_HERE')

Any ideas on what might be causing this intermittent behavior?

i suspect a network issue on the pi. check if the connection is unstable, and add error handling to log exceptions. also, monitor memory usage to rule out resource issues. maybe discord api had a hiccup.

Have you considered implementing a heartbeat mechanism? This could help identify if the bot is truly disconnecting or just experiencing temporary communication issues. You might want to add logging statements throughout your code to pinpoint where exactly the problem occurs. Also, check the Discord API status page for any reported outages or issues that coincide with your bot’s behavior. If the problem persists, you may need to investigate the VPS’s network stability or consider switching to a more reliable hosting solution. Lastly, ensure your bot’s token is properly secured and hasn’t been compromised, as this could lead to unexpected behavior.

Hey there, I’ve dealt with similar issues before. From my experience, it sounds like you might be hitting Discord’s rate limits. The Raspberry Pi’s clock can sometimes drift, causing timing problems with API requests. Try syncing the Pi’s time with an NTP server.

Also, I’d recommend implementing some error handling and reconnection logic. Something like:

while True:
    try:
        await bot.start('YOUR_TOKEN_HERE')
    except discord.errors.HTTPException as e:
        print(f'HTTP error: {e}')
        await asyncio.sleep(60)
    except Exception as e:
        print(f'Unexpected error: {e}')
        await asyncio.sleep(60)

This should help your bot recover from temporary network hiccups or API issues. Don’t forget to import asyncio if you use this approach. Good luck!