def compose_type(request, post_type): if post_type not in dict(Post.TYPES): raise Http404() FormClass = POST_TYPE_MAP.get(post_type) or PostTextForm if request.method == "POST": form = FormClass(request.POST, request.FILES) if form.is_valid(): if not request.me.is_moderator: if Post.check_duplicate(user=request.me, title=form.cleaned_data["title"]): raise ContentDuplicated() is_ok = Post.check_rate_limits(request.me) if not is_ok: raise RateLimitException( title="🙅♂️ Слишком много постов", message= "В последнее время вы создали слишком много постов. Потерпите, пожалуйста." ) post = form.save(commit=False) post.author = request.me post.type = post_type post.save() PostSubscription.subscribe(request.me, post) if post.is_visible: if post.topic: post.topic.update_last_activity() SearchIndex.update_post_index(post) return redirect("show_post", post.type, post.slug) return redirect("compose") else: form = FormClass() return render(request, f"posts/compose/{post_type}.html", { "mode": "create", "form": form })
def continue_posting(update: Update, started_post: dict, user: User): if update.callback_query: if update.callback_query.data == "nope": # cancel posting cached_post_delete(update.effective_user.id) return "Ок, забыли 👌" elif update.callback_query.data in {"post", "link", "question"}: # ask for title started_post["type"] = update.callback_query.data cached_post_set(update.effective_user.id, started_post) return f"Отлично. Теперь надо придумать заголовок, чтобы всем было понятно о чем это. " \ f"Подумайте и пришлите его следующим сообщением 👇" elif update.callback_query.data == "go": # go-go-go, post the post FormClass = POST_TYPE_MAP.get(started_post["type"]) or PostTextForm form = FormClass(started_post) if not form.is_valid(): return f"🤦♂️ Что-то пошло не так. Пришлите нам багрепорт. " \ f"Вот ошибка:\n```{str(form.errors)}```" if Post.check_duplicate(user=user, title=form.cleaned_data["title"]): return "🤔 Выглядит как дубликат вашего прошлого поста. " \ "Проверьте всё ли в порядке и пришлите ниже другой заголовок 👇" is_ok = Post.check_rate_limits(user) if not is_ok: return "🙅♂️ Извините, вы сегодня запостили слишком много постов. Попробуйте попозже" post = form.save(commit=False) post.author = user post.type = started_post["type"] post.meta = {"telegram": update.to_json()} post.save() post_url = settings.APP_HOST + reverse("show_post", kwargs={ "post_type": post.type, "post_slug": post.slug }) cached_post_delete(update.effective_user.id) return f"Запостили 🚀🚀🚀\n\n{post_url}" if update.message: started_post["title"] = str(update.message.text or update.message.caption or "").strip()[:128] if len(started_post["title"]) < 7: send_telegram_message( chat=Chat(id=update.effective_chat.id), text=f"Какой-то короткий заголовок. Пришлите другой, подлинее", reply_markup=telegram.InlineKeyboardMarkup([[ telegram.InlineKeyboardButton("❌ Отменить всё", callback_data=f"nope"), ]])) return cached_post_set(update.effective_user.id, started_post) emoji = Post.TYPE_TO_EMOJI.get(started_post["type"]) or "🔥" send_telegram_message( chat=Chat(id=update.effective_chat.id), text=f"Заголовок принят. Теперь пост выглядит как-то так:\n\n" f"{emoji} <b>{started_post['title']}</b>\n\n" f"{started_post['text'] or ''}\n\n" f"{started_post['url'] or ''}\n\n" f"<b>Будем постить?</b> (после публикации его можно будет подредактировать на сайте)", reply_markup=telegram.InlineKeyboardMarkup([ [ telegram.InlineKeyboardButton("✅ Поехали", callback_data=f"go"), telegram.InlineKeyboardButton("❌ Отмена", callback_data=f"nope"), ], ]))