5

我正在尝试开发一个简单的机器人,它可以从用户那里检索照片,然后对媒体文件进行一些操作。我正在使用 Telebot ( 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

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

4

2 回答 2

9

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

@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”的文件,即您所询问的照片。

于 2017-09-15T14:43:45.807 回答
9

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

# -*- 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>

获取完整的照片 URL

于 2017-03-15T14:06:43.690 回答