通过pyTelegramBotAPI获取telegram bot中的照片

时间:2017-03-14 20:50:26

标签: python python-2.7 telegram-bot python-telegram-bot

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

据我所知,我可以使用特殊处理程序将收入消息除以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

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

2 个答案:

答案 0 :(得分:4)

因此,如果有任何人在Telegram机器人上接收照片时遇到问题,这里的代码可以检索照片的相对文件路径:

# -*- coding: utf-8 -*-

import logging
import flask
import telebot
import sys
import re
import json
import decorator
from subprocess import Popen, PIPE

def externalIP():
    return Popen('wget http://ipinfo.io/ip -qO -', shell=True, stdout=PIPE).stdout.read()[:-1]

TELEBOT_TOKEN = '<token>'
WEBHOOK_HOST = externalIP()
WEBHOOK_PORT = 8443
WEBHOOK_LISTEN = '0.0.0.0'
WEBHOOK_SSL_CERT = 'server.crt'
WEBHOOK_SSL_PRIV = 'server.key'
WEBHOOK_URL_BASE = "https://%s:%s" % (WEBHOOK_HOST, WEBHOOK_PORT)
WEBHOOK_URL_PATH = "/%s/" % (TELEBOT_TOKEN)
bot = telebot.TeleBot(TELEBOT_TOKEN)
app = flask.Flask(__name__)

@decorator.decorator
def errLog(func, *args, **kwargs):
    result = None
    try:
        result = func(*args, **kwargs)
    except Exception as e:
        print e.__repr__()
    return result


@app.route('/', methods=['GET', 'HEAD'])
def index():
    return 'Hello world!'


@app.route(WEBHOOK_URL_PATH, methods=['POST'])
def webhook():
    if flask.request.headers.get('content-type') == 'application/json':
        json_string = flask.request.get_data()
        update = telebot.types.Update.de_json(json_string)
        bot.process_new_messages([update.message])
        return ''
    else:
        flask.abort(403)


@bot.message_handler(content_types=['text'])
def echo(message):
    bot.send_message(message.chat.id, message.text)


@errLog
def processPhotoMessage(message):
    print 'message.photo =', message.photo
    fileID = message.photo[-1].file_id
    print 'fileID =', fileID
    file = bot.get_file(fileID)
    print 'file.file_path =', file.file_path



@bot.message_handler(content_types=['photo'])
def photo(message):
    processPhotoMessage(message)


def main():
    global data
    bot.remove_webhook()
    bot.set_webhook(url=WEBHOOK_URL_BASE + WEBHOOK_URL_PATH,
                    certificate=open(WEBHOOK_SSL_CERT, 'r'))
    app.run(host=WEBHOOK_LISTEN,
            port=8443,
            ssl_context=(WEBHOOK_SSL_CERT, WEBHOOK_SSL_PRIV),
            debug=False)

if __name__ == '__main__':
    main()

使用此模板

https://api.telegram.org/file/bot<token>/<file_path>

获取完整的照片网址

答案 1 :(得分:0)

如果您想下载照片,可以使用以下代码:

@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”的文件,即您要求的照片。