如何在GitHub Actions中解决Telethon无交互登录发送文件问题
解决GitHub Actions无交互环境下Telethon自动登录发送文件问题
问题背景
在GitHub Actions定时运行脚本,通过Telethon使用个人Telegram账号向指定群组发送生成的文件时,遇到无交互环境下登录需要手动输入手机号和验证码的问题,运行时报错:
Run python Send_Telagram_Message.py Traceback (most recent call last): File "Send_Telagram_Message.py", line 33, in <module> with client: File "/opt/hostedtoolcache/Python/3.8.18/x64/lib/python3.8/site-packages/telethon/helpers.py", line 219, in _sync_enter return loop.run_until_complete(self.__aenter__()) File "/opt/hostedtoolcache/Python/3.8.18/x64/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete return future.result() File "/opt/hostedtoolcache/Python/3.8.18/x64/lib/python3.8/site-packages/telethon/client/auth.py", line 657, in __aenter__ return await self.start() File "/opt/hostedtoolcache/Python/3.8.18/x64/lib/python3.8/site-packages/telethon/client/auth.py", line 165, in _start value = phone() File "/opt/hostedtoolcache/Python/3.8.18/x64/lib/python3.8/site-packages/telethon/client/auth.py", line 22, in <lambda> phone: typing.Callable[[], str] = lambda: input('Please enter your phone (or bot token): '), EOFError: EOF when reading a line Please enter your phone (or bot token): Error: Process completed with exit code 1.
用户当前使用的Telethon代码:
from telethon.sync import TelegramClient import os # Set up the Telegram client with your own account credentials api_id = os.environ['API_ID'] api_hash = os.environ['API_HASH'] phone_number = os.environ['PHONE_NUMBER'] client = TelegramClient('send things', api_id, api_hash) async def main(): # Log in to your Telegram account await client.start(phone_number) # Replace 'group_username' with the username of your group group_id = -4119703192 group_entity = await client.get_entity(group_id) # Path to the folder containing images folder_path = os.path.join(current_directory, 'To_Send') # Iterate through the images in the folder for filename in os.listdir(folder_path): if filename.endswith('.jpg') or filename.endswith('.png'): image_path = os.path.join(folder_path, filename) # Send the image to the group await client.send_file(group_entity, file=image_path) print("All images sent to the group.") # Run the main function with client: client.loop.run_until_complete(main())
GitHub Actions工作流配置:
name: Send_Telagram_Message.py on: schedule: - cron: '* * * * *' #10min jobs: run_script: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: 3.8 - name: Install dependencies run: | pip install telethon - name: Run script env: API_ID: ${{ secrets.TELEGRAM_API_ID }} API_HASH: ${{ secrets.TELEGRAM_API_HASH }} PHONE_NUMBER: ${{ secrets.TELEGRAM_PHONE_NUMBER }} run: python Send_Telagram_Message.py
解决方案
1. 本地生成Telethon会话文件
Telethon首次登录后会生成一个.session文件,用于后续自动复用登录状态,无需再次输入手机号和验证码:
- 在本地环境运行你的Telethon脚本,手动完成手机号、验证码(以及两步验证密码,如果开启的话)的输入,运行成功后会在当前目录生成
send things.session文件(文件名对应你代码中TelegramClient的第一个参数)。
2. 存储会话文件
有两种方式将会话文件引入GitHub Actions环境:
方式一:直接加入Git仓库
将生成的send things.session文件添加到你的Git仓库并提交推送。注意:该文件包含你的账号登录信息,若仓库公开存在安全风险,建议使用方式二。
方式二:通过GitHub Secrets存储(更安全)
- 将
send things.session文件编码为base64字符串:base64 "send things.session" > session_base64.txt - 打开GitHub仓库的Settings → Secrets and variables → Actions,新建一个Secret,命名为
TELETHON_SESSION,将session_base64.txt中的内容粘贴进去。
3. 修改Telethon脚本
- 补全缺失的
current_directory变量定义; - 若账号开启两步验证,添加密码参数;
- 确保
client.start()能自动复用会话:
from telethon.sync import TelegramClient import os # 获取当前工作目录 current_directory = os.getcwd() api_id = os.environ['API_ID'] api_hash = os.environ['API_HASH'] phone_number = os.environ['PHONE_NUMBER'] # 若开启两步验证,从环境变量获取密码 telegram_password = os.environ.get('TELEGRAM_PASSWORD') # 客户端会自动加载会话文件,无需重新验证 client = TelegramClient('send things', api_id, api_hash) async def main(): # 启动客户端,会话文件存在时自动登录 await client.start(phone=phone_number, password=telegram_password) group_id = -4119703192 group_entity = await client.get_entity(group_id) folder_path = os.path.join(current_directory, 'To_Send') for filename in os.listdir(folder_path): if filename.endswith('.jpg') or filename.endswith('.png'): image_path = os.path.join(folder_path, filename) await client.send_file(group_entity, file=image_path) print("All images sent to the group.") with client: client.loop.run_until_complete(main())
4. 更新GitHub Actions工作流
- 若使用方式二存储会话文件,添加步骤还原会话文件;
- 若有两步验证密码,添加对应的环境变量:
name: Send_Telagram_Message.py on: schedule: - cron: '*/10 * * * *' # 每10分钟运行一次(修正原cron表达式) jobs: run_script: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: 3.8 - name: Install dependencies run: | pip install telethon # 仅当使用方式二时添加此步骤 - name: Restore Telethon session file run: echo "${{ secrets.TELETHON_SESSION }}" | base64 -d > "send things.session" - name: Run script env: API_ID: ${{ secrets.TELEGRAM_API_ID }} API_HASH: ${{ secrets.TELEGRAM_API_HASH }} PHONE_NUMBER: ${{ secrets.TELEGRAM_PHONE_NUMBER }} TELEGRAM_PASSWORD: ${{ secrets.TELEGRAM_PASSWORD }} # 若开启两步验证则添加 run: python Send_Telagram_Message.py
原理说明
Telethon的.session文件保存了账号的登录会话信息,在无交互环境中,客户端会自动读取该文件完成登录,避免了需要手动输入手机号和验证码的流程,从而解决EOFError问题。
内容的提问来源于stack exchange,提问作者Amin Achak
相关产品推荐
相关产品推荐

