telegram_bots/bots/tasks.py

85 lines
2.7 KiB
Python
Raw Normal View History

2023-12-15 16:03:44 +00:00
import json
import logging
import os
import traceback
2024-09-25 15:37:37 +00:00
from time import sleep
2023-12-15 16:03:44 +00:00
from telegram import Bot, InlineKeyboardMarkup, InlineKeyboardButton
2023-12-16 14:54:02 +00:00
from telegram.error import RetryAfter
2023-12-15 16:03:44 +00:00
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
2024-09-25 15:58:29 +00:00
config._reload()
2023-12-15 16:03:44 +00:00
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,
reply_markup=InlineKeyboardMarkup([[
InlineKeyboardButton('Delete', callback_data=f'del {queued_image_pk}')
]]),
2023-12-15 16:03:44 +00:00
)
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)
2024-09-25 15:37:37 +00:00
sleep(.3)
2023-12-16 14:54:02 +00:00
except RetryAfter as e:
raise self.retry(exc=e, countdown=int(e.retry_after))
2023-12-15 16:03:44 +00:00
except Exception as e:
traceback.print_exc()
raise self.retry(exc=e, countdown=5)
2024-02-29 18:30:05 +00:00
@app.task(bind=True)
def upload_animation_rpc(self, queued_image_pk, fpath, caption):
from .modules.channel_helper import QueuedItem
2024-09-25 15:58:29 +00:00
config._reload()
2024-02-29 18:30:05 +00:00
try:
logging.warning(f'Processing upload task for queued animation 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_animation(
config.tmp_uploads_chat_id,
open(fpath, 'rb'),
caption=caption,
reply_markup=InlineKeyboardMarkup([[
InlineKeyboardButton('Delete', callback_data=f'del {queued_image_pk}')
]]),
2024-02-29 18:30:05 +00:00
)
qi.message_id = m.message_id
qi.args = json.dumps([m.animation.file_id])
qi.save()
else:
bot.send_animation(
qi.config.chat_id,
open(fpath, 'rb'),
caption=caption,
)
qi.processed = True
qi.save()
os.unlink(fpath)
except RetryAfter as e:
raise self.retry(exc=e, countdown=int(e.retry_after))
except Exception as e:
traceback.print_exc()
raise self.retry(exc=e, countdown=5)