Skip to main content
 首页 » 编程设计

python之通过 pyTelegramBotAPI 在电报机器人中获取照片

2025年05月04日23zfyouxi

我正在尝试开发一个简单的机器人,它可以从用户那里检索照片,然后对媒体文件执行多项操作。 我正在使用远程机器人 ( https://github.com/eternnoir/pyTelegramBotAPI ) 进行设计。

据我从 wiki 上看到的,我可以使用特殊的处理程序按 content_type 划分收入消息。

但是,当我写这么简单的方法时:

#main.py 
@bot.message_handler(content_types= ["photo"]) 
def verifyUser(message): 
    print ("Got photo") 
    percent = userFace.verify(message.photo, config.photoToCompare) 
    bot.send_message(message.chat.id, "Percentage: " + str(percent)) 
 
def getData(json_string): 
    updates = telebot.types.Update.de_json(json_string) 
    bot.process_new_updates([updates]) 
 
 
#server.py 
app = Flask(__name__) 
 
@app.route("/", methods=["POST", "GET"]) 
def hello(): 
    json_string = request.get_data() 
    getData(json_string) 
    print("....") 
    print(request.data) 
    return 'test is runing' 
 
if __name__ == '__main__': 
    app.run(host='0.0.0.0') 

我遇到这样的错误,我无法判断是我做错了什么还是 API 有问题

obj = cls.check_json(json_type) 
File "/usr/local/lib/python2.7/dist-packages/telebot/types.py", line 77, in check_json 
return json.loads(json_type) 
File "/usr/lib/python2.7/json/__init__.py", line 339, in loads 
return _default_decoder.decode(s) 
File "/usr/lib/python2.7/json/decoder.py", line 364, in decode 
obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 
File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode 
raise ValueError("No JSON object could be decoded") 
ValueError: No JSON object could be decoded 

我是机器人设计的新手,所以我不知道我是否遵循了正确的方法。我很高兴听到处理照片媒体文件的常见做法。

请您参考如下方法:

如果你想下载照片,你可以使用这段代码:

@bot.message_handler(content_types=['photo']) 
def photo(message): 
    print 'message.photo =', message.photo 
    fileID = message.photo[-1].file_id 
    print 'fileID =', fileID 
    file_info = bot.get_file(fileID) 
    print 'file.file_path =', file_info.file_path 
    downloaded_file = bot.download_file(file_info.file_path) 
 
    with open("image.jpg", 'wb') as new_file: 
        new_file.write(downloaded_file) 

运行此代码后,一个名为“image.jpg”的文件将出现在脚本旁边,这就是您要求的照片。