[英]Get photo in telegram bot through pyTelegramBotAPI
我正在尝试开发一个简单的机器人,它可以从用户那里检索照片,然后对媒体文件进行多项操作。 我正在使用 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 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
如果你想下载照片,你可以使用这段代码:
@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”的文件,该文件是您询问的照片。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.