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

dand1

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

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

车安德鲁

因此,如果有人在使用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>

获取完整的照片网址

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章