Discord Python机器人在共享主机频繁崩溃的原因与解决办法
Hey there, let's break down what's causing your Discord bot to crash daily and fix those issues step by step.
First, let's decode those error messages
Your logs show three key problems working together to take down your bot:
ConnectionResetError(104, 'Connection reset by peer'): This means Discord's WebSocket connection got abruptly dropped by the remote server. This can happen from network blips on your shared host, Discord's temporary server outages, or resource limits on your host disrupting the connection flow.RuntimeError: can't start new thread: Shared hosting plans almost always enforce strict limits on how many threads your processes can create. When your bot tries to reconnect after a disconnect or runs background tasks, it's hitting this thread cap and can't spawn new threads to handle work.- Unclosed client sessions & unretrieved task exceptions: When the connection drops, your bot isn't properly cleaning up its async resources (like the
aiohttpclient session) or handling exceptions from pending tasks. These unaddressed issues pile up and eventually trigger a full crash.
Fixes you can implement right away
Let's tackle these issues with code changes and configuration tweaks:
1. Upgrade your discord.py version
You're using an older version (evidenced by bot.say and Python 3.6) that has known bugs with async resource cleanup. Since your host uses Python 3.6, install the last compatible version of discord.py v1.x:
pip install discord.py==1.7.3 --user
This version fixes many of the unclosed session and task exception bugs.
2. Add robust reconnection handling
Update your code to use modern discord.py patterns and explicit reconnection logic:
token = "This is my Token" prefix = "?" import discord from discord.ext import commands import asyncio import logging # Set up logging to track errors to a file (critical for debugging crashes) logging.basicConfig(filename='bot_errors.log', level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s') bot = commands.Bot(command_prefix=prefix) bot.remove_command("help") @bot.event async def on_ready(): print('Logged in as') print(bot.user.name) print(bot.user.id) print(discord.__version__) print('------') @bot.command(pass_context=True) async def ping(ctx): msg = 'Pong {0.author.mention}'.format(ctx.message) await ctx.send(msg) # Replace bot.say with ctx.send (modern, more reliable) @bot.command(pass_context=True) async def hello(ctx): msg = 'hello... {0.author.mention}'.format(ctx.message) await ctx.send(msg) @bot.event async def on_disconnect(): print("Disconnected from Discord, retrying in 5 seconds...") await asyncio.sleep(5) try: await bot.start(token) except Exception as e: error_msg = f"Reconnection failed: {str(e)}" print(error_msg) logging.error(error_msg) @bot.event async def on_error(event, *args, **kwargs): error_msg = f"Error in event {event}: {args} | {kwargs}" print(error_msg) logging.error(error_msg) # Enable automatic reconnection (discord.py will handle retries for you) bot.run(token, reconnect=True)
3. Avoid hitting thread limits on your shared host
- Stick to async/await: Never use the
threadingmodule in your bot. Discord.py's async pattern uses far fewer system threads than sync code or manual thread spawning. - Use async-compatible libraries: If you add external tools later (like HTTP clients), use async options (e.g.,
aiohttpinstead ofrequests) to avoid hidden thread creation that eats into your host's limit. - Check host metrics: Ask your host for access to resource stats (thread count, CPU, memory) to confirm if thread limits are the root cause. Many shared hosts let you view this via a control panel.
4. Clean up async resources properly
The upgraded discord.py version will handle most of this, but you can reinforce stability by:
- Avoiding manual
aiohttp.ClientSessioncreation unless absolutely necessary (discord.py manages its own session internally). - Using
try/finallyblocks if you do create custom async resources to guarantee cleanup, even if an error occurs.
Bonus: Long-term stability tips
- Review logs regularly: The
loggingsetup in the code above saves errors to a file, so you can go back and see exactly what happened before a crash. - Avoid blocking the event loop: If you add commands that take time to run (like API calls), wrap them in
asyncio.create_task()to keep the bot responsive. - Consider a dedicated host: If shared hosting's resource limits keep causing headaches, a cheap VPS or Discord bot-specific hosting service will give you more control over threads and resources.
内容的提问来源于stack exchange,提问作者Demotry

