提问者:小点点

在电报机器人中从内联模式发送本地照片


我用Python电报机器人API我的机器人。

我想在本地生成照片并将它们作为内联结果发送,但InlineQueryResultPhoto仅接受照片URL。

假设我的项目结构如下所示:

main.py
photo.jpg

如何将photo. jpg作为内联结果发送?

以下是main.py的代码:

from uuid import uuid4
from telegram.ext import InlineQueryHandler, Updater
from telegram import InlineQueryResultPhoto


def handle_inline_request(update, context):
    update.inline_query.answer([
        InlineQueryResultPhoto(
            id=uuid4(),
            photo_url='',  # WHAT DO I PUT HERE?
            thumb_url='',  # AND HERE?
        )
    ])


updater = Updater('TELEGRAM_TOKEN', use_context=True)
updater.dispatcher.add_handler(InlineQueryHandler(handle_inline_request))

updater.start_polling()
updater.idle()

共1个答案

匿名用户

没有直接的答案,因为电报机器人API没有提供它。但是有两个变通方法:您可以使用将照片上传到电报服务器,然后使用InlineQueryResultCachedPhoto或者您可以上传到任何图像服务器,然后使用InlineQueryResultPhoto

第一个选项要求您在创建结果列表之前先将照片上传到电报服务器。您有哪些选项?机器人可以向您发送照片,获取该信息并使用您需要的东西。另一个选项是创建一个私人频道,您的机器人可以在其中发布它将重复使用的照片。此方法的唯一细节是了解channel_id(如何获得私人电报频道的chat_id?)。

现在让我们看一些代码:

from config import tgtoken, privchannID
from uuid import uuid4
from telegram import Bot, InlineQueryResultCachedPhoto

bot = Bot(tgtoken)
def inlinecachedphoto(update, context):
    query = update.inline_query.query
    if query == "/CachedPhoto":
        infophoto = bot.sendPhoto(chat_id=privchannID,photo=open('logo.png','rb'),caption="some caption")
        thumbphoto = infophoto["photo"][0]["file_id"]
        originalphoto = infophoto["photo"][-1]["file_id"]
        results = [
            InlineQueryResultCachedPhoto(
                id=uuid4(),
                title="CachedPhoto",
                photo_file_id=originalphoto)
            ]
        update.inline_query.answer(results)

当您将照片发送到聊天/群组/频道时,您可以获得file_id、缩略图的file_id、标题和我要跳过的其他详细信息。有什么问题吗?如果您没有过滤正确的查询,您可能最终会多次将照片发送到您的私人频道。这也意味着自动完成将不起作用。

另一种选择是将照片上传到互联网,然后使用url。除了自己的托管等选项,您可以使用一些提供API的免费图像托管(例如:imgur、imgbb)。对于这段代码,在imgbb中生成自己的密钥比imgur更简单。一旦生成:

import requests
import json
import base64
from uuid import uuid4
from config import tgtoken, key_imgbb
from telegram import InlineQueryResultPhoto

def uploadphoto():
    with open("figure.jpg", "rb") as file:
        url = "https://api.imgbb.com/1/upload"
        payload = {
            "key": key_imgbb,
            "image": base64.b64encode(file.read()),
        }
        response = requests.post(url, payload)
        if response.status_code == 200:
            return {"photo_url":response.json()["data"]["url"], "thumb_url":response.json()["data"]["thumb"]["url"]}
    return None

def inlinephoto(update, context):
    query = update.inline_query.query
    if query == "/URLPhoto":
        upphoto = uploadphoto()
        if upphoto:
            results = [
                InlineQueryResultPhoto(
                    id=uuid4(),
                    title="URLPhoto",
                    photo_url=upphoto["photo_url"],
                    thumb_url=upphoto["thumb_url"])
                ]
            update.inline_query.answer(results)

此代码类似于前面的方法(并且包含相同的问题):如果您不过滤查询并且在编写内联时不会自动完成,则会上传多次。

这两段代码的编写都认为您要上传的图像是在您收到查询时生成的,否则您可以在接收查询之前完成工作,将该信息保存在数据库中。

您可以运行自己的机器人来获取您的私人频道的channel_idpyTelegram BotAPI

import telebot

bot = telebot.TeleBot(bottoken)

@bot.channel_post_handler(commands=["getchannelid"])
def chatid(message):
    bot.reply_to(message,'channel_id = {!s}'.format(message.chat.id))

bot.polling()

要获取id,您需要在通道/getchannelid@botname中写入