我为自己的机器人使用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
。
第一个选项要求您在创建结果列表之前,先将照片上传到电报服务器。您有哪些选择?机器人可以向您发送照片,获取信息并使用您所需的信息。另一个选择是创建一个私人渠道,您的机器人可以在其中发布将重用的照片。此方法的唯一详细信息是了解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)
当您将照片发送到聊天/群组/频道时,您可以获取文件名,缩略图的文件名,标题以及我将要跳过的其他详细信息。什么问题 如果您没有过滤正确的查询,则可能最终将照片多次发送到您的私人频道。这也意味着自动完成功能将无法正常工作。
另一种选择是将照片上传到互联网,然后使用网址。除了您自己的托管之类的选项之外,您可以使用一些提供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)
此代码与以前的方法相似(并且包含相同的问题):如果您不过滤查询并且在编写内联时没有自动完成功能,则需要多次上传。
编写这两个代码都认为您要上传的图像是在收到查询时生成的,否则,您可以在收到查询之前先做一些工作,然后将该信息保存在数据库中。
您可以运行自己的漫游器以使用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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句