簡體   English   中英

在電報機器人中從內聯模式發送本地照片

[英]Send a local photo from inline mode in a telegram bot

我為我的機器人使用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()

沒有直接答案,因為 Telegram Bot API 不提供它。 但是有兩種解決方法:您可以使用將照片上傳到電報服務器然后使用InlineQueryResultCachedPhoto或者您可以上傳到任何圖像服務器然后使用InlineQueryResultPhoto

InlineQueryResultCachedPhoto

第一個選項要求您在創建結果列表之前先將照片上傳到電報服務器。 你有哪些選擇? 機器人可以向您發送照片,獲取該信息並使用您需要的內容。 另一種選擇是創建一個私人頻道,您的機器人可以在其中發布它將重復使用的照片。 此方法的唯一細節是了解 channel_id( 如何獲取私人 Telegram 頻道的 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、標題和我將跳過的其他詳細信息。 什么問題? 如果您沒有過濾正確的查詢,您最終可能會多次將照片發送到您的私人頻道。 這也意味着自動完成將不起作用。

內聯查詢結果圖片

另一種選擇是將照片上傳到互聯網,然后使用網址。 排除諸如您自己的托管之類的選項,您可以使用一些提供 API 的免費圖像托管(例如:imgur、imgbb)。 對於這段代碼,在imgbb中生成自己的key比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)

此代碼類似於之前的方法(並且包含相同的問題):如果不過濾查詢,則上傳多次,並且在編寫內聯時不會自動完成。

免責聲明

編寫這兩個代碼時都認為您要上傳的圖像是在您收到查詢時生成的,否則您可以在收到查詢之前進行工作,將該信息保存在數據庫中。

獎金

您可以運行自己的機器人以使用 pyTelegramBotAPI 獲取您的私人頻道的 channel_id

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM