【问题标题】:How to receive images from Telegram Bot [duplicate]如何从 Telegram Bot 接收图像 [重复]
【发布时间】:2018-06-30 08:12:00
【问题描述】:

无法从我的电报机器人接收图像,尝试这样的事情:

import telegram
from telegram.ext import Updater
from telegram.ext import MessageHandler
from telegram.ext import Filters

def photo_handler(bot, update):
    file = bot.getFile(update.message.photo.file_id)
    print ("file_id: " + str(update.message.photo.file_id))
    file.download('photo.jpg')

updater = Updater(token='my token')
dispatcher = updater.dispatcher
dispatcher.add_handler(MessageHandler(Filters.photo, photo_handler))

运行时没有任何错误

【问题讨论】:

  • 我已经回答了这个问题how save photo in telegram python bot?。 photo_handler 中的第一行必须是 file = bot.getFile(update.message.photo[-1].file_id)。
  • @dev4Fun ,如果您要向电报发送多个图像怎么办?我们如何处理这种情况?

标签: python python-telegram-bot


【解决方案1】:

我用它来发送由 matplotlib 生成的图像。您可以根据自己的需要进行调整。

import telegram
from telegram.bot import Bot
import yachain
import cStringIO
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np

cfg = yachain.Config().load("telegram.cfg")

token = cfg["token"]
chat_id = cfg["chatID"]

bot = Bot(token=token)

y = [2,4,6,8,10,12,14,16,18,20]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
plt.title('Legend inside')
ax.legend()
#plt.show()

buffer = cStringIO.StringIO()
fig.savefig(buffer, format='png')

buffer.seek(0)
bot.send_photo(chat_id=chat_id,
               photo=buffer)

【讨论】:

  • 关于如何接收照片而不是如何发送照片的问题
  • 是的,我刚发帖就注意到了。我对此发表了评论,但该评论不知何故消失了
  • 谁能帮我解决这个问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-02
  • 1970-01-01
  • 1970-01-01
  • 2015-09-19
  • 2017-01-05
  • 2020-07-16
  • 1970-01-01
相关资源
最近更新 更多