如何通过python-telegram-bot发送照片

时间:2018-07-07 11:47:30

标签: python telegram telegram-bot python-telegram-bot

我希望该代码在用户按下/ start命令后发送照片,但此方法不起作用,任何人都可以帮助我。 谢谢

import emoji, telegram
from telegram.ext import Updater
from telegram.ext import CommandHandler, CallbackQueryHandler
from telegram import InlineKeyboardButton, InlineKeyboardMarkup

token = "-----------"
bot = telegram.Bot(token=token)

pic = "./photo.png"
try:
    chat_id = bot.get_updates()[-1].message.chat_id
except IndexError:
    chat_id = 0

#general functions
def start(bot, update):
    bot.send_photo(chat_id, pic)
    update.message.reply_text(text="helo",
                              reply_markup=menu_keyboard())

2 个答案:

答案 0 :(得分:0)

您的问题是send_photo(chat_id, pic)函数的第二个参数应该是file id,而不是您正在执行的文件名(参见doc)。

您只需更改:

 bot.send_photo(chat_id, pic)

作者

bot.send_photo(chat_id, open(pic,'rb'))

答案 1 :(得分:0)

bot.send_photo方法接受电报服务器上的文件对象或文件ID作为照片参数,因此您应该传递类似open(pic, "rb")的信息,而不是简单地传递pic。 / p>

首次发送照片后,您可以从响应中获取照片的电报文件ID。 传递Telegram的文件ID而不是传递文件对象的速度更快,因为只需将Telegram指向它已经拥有的文件,而不是一次又一次地读取和发送相同的文件。

您可以查找文档here

相关问题