我有带有电报机器人令牌的标准 .env 文件,例如:
BOT_TOKEN = <bot_token>
此外,还有一个 config_reader 文件应该解析 .env 文件以获取令牌:
from pydantic_settings import BaseSettings, SettingsConfigDict
from pydantic import SecretStr
class Settings(BaseSettings):
bot_token: SecretStr
model_config = SettingsConfigDict(env_file='.env', env_file_encoding='utf-8')
config = Settings()
主要的bot.py代码:
async def main():
bot = Bot(token=config.bot_token.get_secret_value(), parse_mode="HTML")
dp = Dispatcher()
logging.basicConfig(filename="bot_logging.log", encoding="utf-8",
format="%(asctime)s %(message)s", datefmt="%m/%d/%Y %H:%M:%S",
level=logging.INFO)
dp.include_routers(messages.router, different_types.router)
await bot.delete_webhook(drop_pending_updates=True)
await dp.start_polling(bot)
当我启动主文件时,出现以下错误:
__pydantic_self__.__pydantic_validator__.validate_python(data, self_instance=__pydantic_self__)
pydantic_core._pydantic_core.ValidationError: 1 validation error for Settings
bot_token
Field required [type=missing, input_value={}, input_type=dict]
我将以下两行添加到我的文件中,与您的文件类似,一切正常!
从 dotenv 导入 load_dotenv
load_dotenv()