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

Telethon Telegram bot点击回调按钮发送指定数量随机照片报错问询

报错原因
  • 核心问题是你向event.reply的file参数仅传入了文件名fotorandom,没有拼接完整的文件路径。程序运行时默认会从当前工作目录查找文件,而你存储图片的目录C:\Users\x\Desktop\Nuova cartella (2)和程序运行目录不一致,导致无法定位到文件,因此抛出了文件不存在的报错。
  • 额外隐藏问题:你使用全局变量i作为计数器,多次触发回调时i不会自动重置,会导致后续请求发送的图片数量不符合预期。
修复方案

你需要给file参数传入图片的完整绝对路径,同时替换全局计数器为局部变量避免计数异常,修复后的代码如下:

import os
import random
from telethon import events

# 提前定义图片存储目录为常量,避免重复书写路径出错
PHOTO_DIR = r"C:\Users\x\Desktop\Nuova cartella (2)"

@bot.on(events.CallbackQuery)
async def handler(event):
    global fotomandate
    if event.data == b"1":
        await event.respond("how many photos do i send?") 
        numerofoto = int(input("how many photos do i send?")) ##ignore this line i'll fix later
        print(numerofoto)
        # 提前遍历目录生成所有图片的完整路径列表,避免循环中重复遍历目录
        all_photos = [
            os.path.join(PHOTO_DIR, filename)
            for filename in os.listdir(PHOTO_DIR)
            if os.path.isfile(os.path.join(PHOTO_DIR, filename))
        ]
        count = 0
        while count < numerofoto:
            fotorandom = random.choice(all_photos)
            count += 1
            await event.reply(file=fotorandom)

本次修改主要涉及两点:

  1. 提前遍历图片目录,生成所有图片的完整绝对路径列表,随机选择后直接将完整路径传入file参数,保证程序可以正确定位到图片文件
  2. 移除全局变量i,使用局部变量count作为计数器,每次触发回调都会从0开始计数,避免多次触发回调时计数错乱

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 06:06:01