async channel helper sending

This commit is contained in:
bakatrouble 2023-12-15 19:03:44 +03:00
parent b04dfeda4c
commit 043ee029d2
2 changed files with 47 additions and 9 deletions

View File

@ -17,6 +17,7 @@ from jsonrpc import Dispatcher as RPCDispatcher
from djconfig import config
from bots.models import TelegramBotModuleConfig, BotUser
from bots.tasks import upload_image_rpc
class ChannelHelperBotModuleConfig(TelegramBotModuleConfig):
@ -58,15 +59,15 @@ class ChannelHelperBotModuleConfig(TelegramBotModuleConfig):
if width > 2000 or height > 2000:
im.thumbnail((2000, 2000))
im = im.convert('RGB')
with tempfile.TemporaryDirectory() as d:
fpath = os.path.join(d, '{}.jpg'.format(uuid4()))
im.save(fpath)
if self.queued:
m = bot.send_photo(config.tmp_uploads_chat_id, open(fpath, 'rb'), caption=note or None)
QueuedItem.objects.create(config=self, type='photo', args=json.dumps([m.photo[-1].file_id]), message_id=m.message_id, image_hash=image_hash)
else:
bot.send_photo(self.chat_id, open(fpath, 'rb'))
QueuedItem.objects.create(config=self, type='photo', args=json.dumps([]), image_hash=image_hash, processed=True)
fpath = os.path.join(tempfile.gettempdir(), '{}.jpg'.format(uuid4()))
im.save(fpath)
qi = QueuedItem.objects.create(config=self, type='photo', args=json.dumps([]), message_id=None, image_hash=image_hash)
upload_image_rpc.apply_async(qi.pk, fpath, note or None)
# if self.queued:
# m = bot.send_photo(config.tmp_uploads_chat_id, open(fpath, 'rb'), caption=note or None)
# else:
# bot.send_photo(self.chat_id, open(fpath, 'rb'))
# QueuedItem.objects.create(config=self, type='photo', args=json.dumps([]), image_hash=image_hash, processed=True)
return True
def periodic_task(self, bot: Bot):

37
bots/tasks.py Normal file
View File

@ -0,0 +1,37 @@
import json
import logging
import os
import traceback
from config.celery import app
from djconfig import config
@app.task(bind=True)
def upload_image_rpc(self, queued_image_pk, fpath, caption):
from .modules.channel_helper import QueuedItem
try:
logging.warning(f'Processing upload task for queued item #{queued_image_pk}')
qi = QueuedItem.objects.get(pk=queued_image_pk)
bot = qi.config.bot.get_bot()
if qi.config.queued:
m = bot.send_photo(
config.tmp_uploads_chat_id,
open(fpath, 'rb'),
caption=caption,
)
qi.message_id = m.message_id
qi.args = json.dumps([m.photo[-1].file_id])
qi.save()
else:
bot.send_photo(
qi.config.chat_id,
open(fpath, 'rb'),
caption=caption,
)
qi.processed = True
qi.save()
os.unlink(fpath)
except Exception as e:
traceback.print_exc()
raise self.retry(exc=e, countdown=5)