下载图片

This commit is contained in:
luotuan
2023-02-26 17:56:00 +08:00
parent 3247d4e365
commit 7f35062d33
2 changed files with 46 additions and 6 deletions

View File

@@ -3,15 +3,17 @@ from concurrent.futures import ThreadPoolExecutor
import io
import requests
import telebot
from common import const
from common.log import logger
from channel.channel import Channel
BOT_TOKEN = '5684663516:AAFRYGIcDalEZzExyoBwt-t33BZjxcTISxg'
bot = telebot.TeleBot(BOT_TOKEN)
from config import channel_conf_val, channel_conf
bot = telebot.TeleBot(token=channel_conf(const.TELEGRAM).get('bot_token'))
thread_pool = ThreadPoolExecutor(max_workers=8)
@bot.message_handler(commands=['ask'])
@bot.message_handler(content_types=['text'])
def send_welcome(msg):
# telegram消息处理
TelegramChannel().handle(msg)
class TelegramChannel(Channel):
@@ -22,10 +24,45 @@ class TelegramChannel(Channel):
bot.infinity_polling()
def handle(self, msg):
logger.debug("[Telegram]receive msg: " + msg.text)
thread_pool.submit(self._dosend,msg.text.replace("/ask",""),msg)
img_match_prefix = self.check_prefix(msg, channel_conf_val(const.TELEGRAM, 'image_create_prefix'))
if img_match_prefix:
thread_pool.submit(self._do_send_img, msg, str(msg.chat.id))
else:
thread_pool.submit(self._dosend,msg.text,msg)
def _dosend(self,query,msg):
context= dict()
context['from_user_id'] = '1111'
context['from_user_id'] = str(msg.chat.id)
reply_text = super().build_reply_content(query, context)
logger.info('[Telegram]] reply content: {}'.format(reply_text))
bot.reply_to(msg,reply_text)
bot.reply_to(msg,reply_text)
def _do_send_img(self, msg, reply_user_id):
try:
if not msg:
return
context = dict()
context['type'] = 'IMAGE_CREATE'
img_url = super().build_reply_content(msg.text, context)
if not img_url:
return
# 图片下载
pic_res = requests.get(img_url, stream=True)
image_storage = io.BytesIO()
for block in pic_res.iter_content(1024):
image_storage.write(block)
image_storage.seek(0)
# 图片发送
logger.info('[Telegrame] sendImage, receiver={}'.format(reply_user_id))
bot.reply_to(msg, image_storage)
except Exception as e:
logger.exception(e)
def check_prefix(self,msg,prefix_list):
for prefix in prefix_list:
if msg.text.startswith(prefix):
return prefix
return None

View File

@@ -30,6 +30,9 @@
"subject_keyword": ["bot", "@bot"],
"host_email": "xxxx@gmail.com",
"host_password": "GMAIL ACCESS KEY"
},
"telegram":{
"bot_token": "5684663516:AAFRYGIcDalEZzExyoBwt-t33BZjxcTISxg"
}
}
}