Telegram Bot中environ环境变量无法跨文件传递的问题
Telegram Bot环境变量导入异常与命令无响应问题解决
问题概述
loader.py可正常读取环境变量TOKEN,但start_message.py导入bot/dp时触发ImproperlyConfigured: Set the TOKEN environment variable错误- 启动入口
main.py无报错,但Bot完全不响应/start命令 - 尝试在handler文件中重复初始化环境变量无效,仅重复定义bot能临时解决,但不符合代码复用原则
项目文件结构
my_project ├──__pycache__ ├── .spyproject ├──core │ ├──__init__.py │ ├──functions │ │ └──__init__.py │ │ └──notify_admins.py │ └──handlers │ └──__init__.py │ └──start_message.py ├──data │ └──.env ├──venv ├──environment.py ├──loader.py └──main.py
相关代码片段
environment.py
import environ import pathlib env = environ.Env(DEBUG=(bool, False)) current_dir = pathlib.Path(__file__).resolve().parent env_file = pathlib.Path(current_dir, "./data/.env") with open(env_file, 'r') as fd: environ.Env.read_env(env_file=fd) TOKEN = env("TOKEN") admin_chat = env("admin_chat")
loader.py
from aiogram import Bot, Dispatcher import environ from environment import TOKEN bot = Bot(token=TOKEN) dp = Dispatcher(bot)
start_message.py
from aiogram import types from loader import bot, dp @dp.message_handler(commands=["start"]) async def send_start_message(message: types.Message): await bot.send_message(message.chat.id, "Hello!")
notify_admins.py
from loader import bot, dp from aiogram import types from datetime import datetime from environment import admin_chat admin_chat = int(admin_chat) @dp.message_handler(commands=["start"]) async def send_startup_message_to_admins(message: types.Message): await bot.send_message(admin_chat, f"[{datetime.now()}] Bot was started by" \ f"@{message.from_user.username}, " \ f"ID: {message.from_user.id}")
main.py
from aiogram import executor import nest_asyncio nest_asyncio.apply() if __name__ == "__main__": from handlers import dp executor.start_polling(dp)
完整错误栈
runfile('/home/user/***/handlers/start_message.py', wdir='/home/user/***/handlers', current_namespace=True) Traceback (most recent call last): File ~/***/venv/lib/python3.10/site-packages/environ/environ.py:275 in get_value value = self.ENVIRON[var] File /usr/lib/python3.10/os.py:679 in __getitem__ raise KeyError(key) from None KeyError: 'TOKEN' During handling of the above exception, another exception occurred: Traceback (most recent call last): File ~/***/venv/lib/python3.10/site-packages/spyder_kernels/py3compat.py:356 in compat_exec exec(code, globals, locals) File ~/***/handlers/start_message.py:9 from loader import bot, dp File ~/***/loader.py:14 bot = Bot(token=env("TOKEN")) File ~/***/venv/lib/python3.10/site-packages/environ/environ.py:125 in __call__ return self.get_value(var, cast=cast, default=default, parse_default=parse_default) File ~/***/venv/lib/python3.10/site-packages/environ/environ.py:279 in get_value raise ImproperlyConfigured(error_msg) ImproperlyConfigured: Set the TOKEN environment variable
解决方案
1. 修复环境变量加载逻辑
错误根源:实际运行的loader.py中直接调用了未加载.env文件的env("TOKEN")(与提供的代码不一致),且直接运行handler文件时工作目录异常。
- 确保
loader.py严格使用environment.py中预加载的TOKEN,删除冗余的environ导入:from aiogram import Bot, Dispatcher from environment import TOKEN bot = Bot(token=TOKEN) dp = Dispatcher(bot)
2. 注册所有Handler
Bot不响应命令是因为handlers/__init__.py未导入定义好的handler,导致路由未注册。修改core/handlers/__init__.py:
from loader import dp from .start_message import * from ..functions.notify_admins import *
3. 统一启动入口
禁止直接运行handler文件,必须通过main.py启动Bot,确保工作目录为项目根目录,避免路径解析错误。
4. 额外校验
- 确认
data/.env文件存在,且包含TOKEN=你的机器人令牌和admin_chat=管理员聊天ID - 若导入路径仍有问题,可在
main.py开头添加路径补全:import sys, os sys.path.append(os.path.dirname(os.path.abspath(__file__)))
内容的提问来源于stack exchange,提问作者Ani
相关产品推荐
相关产品推荐

