I'm trying to develop a simple bot, that can retrieve photo from user and then do several operations with media file. I'm using telebot (https://github.com/eternnoir/pyTelegramBotAPI) for design.
As far as I can see from the wiki, I can divide income messages by content_type
using special handlers.
However, when I wrote such simple method:
#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')
I get such mistake which I can't classify whether I'm doing something wrong or there is a problem with 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
I'm new to bot design, so I don't know, whether I'm following the right way. I will be glad to hear the common practice of working with photo media files.
To create a Telegram bot, we need to download Telegram and create a user account. You can use Telegram from either your PC or your phone, or both. Once you have a Telegram account, you can register a new bot by sending a message to BotFather, a bot managed by Telegram themselves.
So if anyone ever has problems with receiving photos on a Telegram bot, here's the code that can retreive a relative file path to the photo:
# -*- 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()
Use this template
https://api.telegram.org/file/bot<token>/<file_path>
To get the full photo URL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With