You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行Telethon编写的Telegram bot代码报OperationalError无法打开数据库文件

问题排查与修复方案

错误翻译与原因

报错信息 Operational Error : unable to open database file 翻译为:操作错误:无法打开数据库文件
该错误触发的核心原因是:Telethon初始化客户端时会在指定路径下创建sqlite格式的会话存储文件,你代码中指定的会话存储目录为session/,如果该目录未提前创建,系统无法在不存在的目录下新建文件,就会抛出该错误。

修复方案

  • 新增os模块引用,在使用会话目录前先判断目录是否存在,不存在则自动创建
  • 确认执行代码的用户对当前项目目录有读写权限,避免权限不足无法创建文件
  • 检查config.json中的phone字段没有包含系统文件名禁止的特殊字符(如/、\、:、*等),避免生成非法路径

修改后的完整代码

from telethon import TelegramClient, connection
import logging
from telethon import sync, TelegramClient, events
import json
import os

with open('config.json', 'r') as f:
    config = json.loads(f.read())

logging.basicConfig(level=logging.WARNING)

accounts = config['accounts']

folder_session = 'session/'
# 自动创建会话存储目录
if not os.path.exists(folder_session):
    os.makedirs(folder_session)

for account in accounts:
    api_id = account['api_id']
    api_hash = account['api_hash']
    phone = account['phone']
    print(phone)

    client = TelegramClient(folder_session + phone, api_id, api_hash)
    client.start()
    if client.is_user_authorized():
        print('登录成功')
    else:
        print('登录失败')
    client.disconnect()

内容的提问来源于stack exchange,提问作者kunal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 07:18:01