如何修复Heroku上的ModuleNotFoundError: No module named 'discord'错误
Hey there! Let’s figure out why your Discord bot isn’t launching on Heroku. I took a look at the log screenshot you shared, and here’s what’s going wrong and how to fix it:
First, Let’s Break Down the Log Error
The key issue in your logs points to either a missing dependency (super common with Heroku deployments) or a misconfigured startup command. Let’s walk through the fixes step by step:
1. Make Sure Your Dependencies Are Listed Correctly
Heroku relies on a file in your GitHub repo to know which libraries to install for your bot. Depending on what language you’re using:
- If you’re using Python: You need a
requirements.txtfile in your repo’s root. Double-check that your Discord library (likediscord.py) is listed here with the right version. If it’s missing, add a line likediscord.py==2.3.2, save the file, commit it to GitHub, and push the changes. - If you’re using Node.js: You need a
package.jsonfile withdiscord.jsin the dependencies section. If it’s not there, runnpm install discord.js --saveon your local machine, then commit the updatedpackage.jsonandpackage-lock.jsonto GitHub.
Pro tip: Don’t forget to commit these files—Heroku can’t install libraries it can’t see!
2. Check Your Procfile
Heroku uses a Procfile (no file extension, exact name) to know how to start your bot. It needs to be in your repo’s root:
- Python example:
worker: python bot.py(replacebot.pywith your actual main bot script name) - Node.js example:
worker: node bot.js
If you don’t have a Procfile, create one with the correct line, commit it, and push to GitHub.
3. Turn On the Worker Dyno
Even if your Procfile is perfect, Heroku might not be running the worker dyno by default:
- Head to your Heroku app’s dashboard, go to the Resources tab.
- Find the
workerdyno option and toggle it on (you’ll need to confirm the change). Free tier users get one free worker dyno, so this won’t cost you anything.
4. Verify Your Bot Token Setup
Make sure your Discord bot token is stored as a config variable in Heroku (never hardcode it in your repo!):
- Go to your Heroku app’s Settings tab, then scroll to Config Vars.
- Add a variable (name it something like
DISCORD_TOKEN) and paste your bot’s token as the value. - Double-check that your bot code pulls the token from this environment variable. For example:
- Python:
os.getenv('DISCORD_TOKEN') - Node.js:
process.env.DISCORD_TOKEN
- Python:
Final Step: Redeploy
After fixing any of the above, commit your changes to GitHub, then go to Heroku’s Deploy tab and click Deploy Branch to start a fresh deployment. Check the logs again to see if the error is gone.
If you still hit snags, share the exact error message from the logs and I’ll help you dig deeper!
内容的提问来源于stack exchange,提问作者Cupcake

