【发布时间】:2017-12-31 00:15:59
【问题描述】:
我正在编写一个电报机器人作为一个更大项目的一部分,但我似乎无法让机器人在每次下载图像时都写入一个新文件,而是覆盖它收到的第一个图像。
我遇到的另一个问题是它无需用户输入 /photo 就可以下载图像,我不介意,所以我们称它为“功能”,但如果这是原因,请向我解释
提前谢谢帮助
import logging
from telegram.ext import MessageHandler, Filters
from telegram.ext import Updater
import os
import os.path
import datetime
import sys
updater = Updater(token= 'omitted')
from telegram.ext import Updater, CommandHandler
time = datetime.datetime.now().strftime("%d-%m-%y_%H:%M,%S")
def start(bot, update):
update.message.reply_text('Hello World!')
def hello(bot, update):
update.message.reply_text(
'Hello {}'.format(update.message.from_user.first_name))
def photo(bot, update):
save_path = '/Users/barthofman/Desktop/grandtest/'
file_id = update.message.photo[-1].file_id
newFile = bot.getFile(file_id)
newFile.download(os.path.join(save_path, time+'.jpg'))
bot.sendMessage(chat_id=update.message.chat_id, text="download succesful")
filename = (time+'jpg')
with open(filename,"rb") as f:
Jpegcontents = (f.read())
if Jpegcontents.startswith(b"\xff\xd8") and Jpegcontents.endswith(b"\xff\xd9"):
bot.sendMessage(chat_id=update.message.chat_id, text="Valid Image")
if not Jpegcontents.startswith(b"\xff\xd8") and Jpegcontents.endswith(b"\xff\xd9"):
os.system("rm ",filename)
photo_handler = MessageHandler(Filters.photo, photo)
updater.dispatcher.add_handler(photo_handler)
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CommandHandler('hello', hello))
updater.start_polling()
updater.idle()
updater.stop()
【问题讨论】:
-
我强烈建议您生成一个新的身份验证令牌。它们应该保密。
-
你不应该在def photo里面设置时间变量吗?
-
...天哪,你是对的,完全错过了
标签: python python-2.7 telegram python-telegram-bot