Skip to content

Commit

Permalink
add eng weekly rewards
Browse files Browse the repository at this point in the history
  • Loading branch information
ohld committed Jun 9, 2024
1 parent 251f4d2 commit 54bd1af
Show file tree
Hide file tree
Showing 5 changed files with 179 additions and 17 deletions.
15 changes: 13 additions & 2 deletions flow_deployments/rewards.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,25 @@

from src.config import settings
from src.flows.rewards.uploaded_memes import (
reward_en_users_for_weekly_top_uploaded_memes,
reward_ru_users_for_weekly_top_uploaded_memes,
)

deployment_user_stats = Deployment.build_from_flow(
deployment_weekly_top_uploaded_memes_ru = Deployment.build_from_flow(
flow=reward_ru_users_for_weekly_top_uploaded_memes,
name="Reward RU users for weekly top uploaded memes",
schedules=[CronSchedule(cron="0 19 * * 5", timezone="Europe/London")],
work_pool_name=settings.ENVIRONMENT,
)

deployment_user_stats.apply()
deployment_weekly_top_uploaded_memes_ru.apply()


deployment_weekly_top_uploaded_memes_en = Deployment.build_from_flow(
flow=reward_en_users_for_weekly_top_uploaded_memes,
name="Reward EN users for weekly top uploaded memes",
schedules=[CronSchedule(cron="0 18 * * 3", timezone="Europe/London")],
work_pool_name=settings.ENVIRONMENT,
)

deployment_weekly_top_uploaded_memes_en.apply()
18 changes: 11 additions & 7 deletions src/flows/rewards/daily.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,23 @@
async def reward_user_for_daily_activity(user_id: int):
user_info = await get_user_info(user_id)
if user_info["memes_watched_today"] == 10:
res = await pay_if_not_paid(
balance = await pay_if_not_paid(
user_id,
TrxType.DAILY_REWARD,
datetime.today().strftime("%Y-%m-%d"),
)
if res:
msg = localizer.t(
"rewards.daily_reward",
user_info["interface_lang"],
).format(amount=PAYOUTS[TrxType.DAILY_REWARD])
if balance:
interface_lang = user_info["interface_lang"]
nmemes_sent = user_info["nmemes_sent"]

msg = localizer.t("rewards.daily_reward", interface_lang).format(
amount=PAYOUTS[TrxType.DAILY_REWARD]
)
await bot.send_message(
user_id,
msg,
parse_mode=ParseMode.HTML,
)
await log(msg)
await log(
f"+daily to #{user_id}: {interface_lang}, {balance} 🍔, {nmemes_sent} 📮" # noqa E501
)
38 changes: 34 additions & 4 deletions src/flows/rewards/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from src.database import fetch_all


async def get_all_uploaded_memes_weerly_ru() -> list[dict[str, Any]]:
async def get_all_uploaded_memes_weekly_ru() -> list[dict[str, Any]]:
select_statement = """
SELECT
M.id meme_id,
Expand All @@ -27,9 +27,39 @@ async def get_all_uploaded_memes_weerly_ru() -> list[dict[str, Any]]:
ON U.id = S.added_by
WHERE 1=1
AND S.type = 'user upload'
AND M.status = 'ok'
AND M.created_at > NOW() - INTERVAL '7 days'
AND (UL.language_code = 'ru' OR M.language_code = 'ru')
AND M.status IN ('ok', 'published')
AND M.created_at >= NOW() - INTERVAL '7 days'
AND M.language_code = 'ru'
AND MS.nmemes_sent >= 10
"""
return await fetch_all(text(select_statement))


async def get_all_uploaded_memes_weekly_en() -> list[dict[str, Any]]:
select_statement = """
SELECT
M.id meme_id,
M.status,
M.telegram_file_id,
S.added_by AS author_id,
U.nickname,
MS.nmemes_sent,
MS.nlikes,
MS.ndislikes
FROM meme M
LEFT JOIN meme_source S
ON M.meme_source_id = S.id
LEFT JOIN meme_stats MS
ON M.id = MS.meme_id
LEFT JOIN user_language UL
ON S.added_by = UL.user_id
LEFT JOIN "user" U
ON U.id = S.added_by
WHERE 1=1
AND S.type = 'user upload'
AND M.status IN ('ok', 'published')
AND M.created_at >= NOW() - INTERVAL '7 days'
AND M.language_code = 'en'
AND MS.nmemes_sent >= 10
"""
return await fetch_all(text(select_statement))
122 changes: 120 additions & 2 deletions src/flows/rewards/uploaded_memes.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,16 @@
from src.crossposting.service import (
log_meme_sent,
)
from src.flows.rewards.service import get_all_uploaded_memes_weerly_ru
from src.flows.rewards.service import (
get_all_uploaded_memes_weekly_en,
get_all_uploaded_memes_weekly_ru,
)
from src.storage.constants import MemeStatus
from src.storage.service import update_meme
from src.tgbot.bot import bot
from src.tgbot.constants import (
TELEGRAM_CHANNEL_EN_CHAT_ID,
TELEGRAM_CHANNEL_EN_LINK,
TELEGRAM_CHANNEL_RU_CHAT_ID,
TELEGRAM_CHANNEL_RU_LINK,
)
Expand Down Expand Up @@ -47,7 +52,7 @@ async def reward_ru_users_for_weekly_top_uploaded_memes():
logger = get_run_logger()
logger.info("Going to reward users for weekly top uploaded memes")

uploaded_memes = await get_all_uploaded_memes_weerly_ru()
uploaded_memes = await get_all_uploaded_memes_weekly_ru()
logger.info(f"Received {len(uploaded_memes)} uploaded memes")

if len(uploaded_memes) < 5:
Expand Down Expand Up @@ -153,3 +158,116 @@ async def reward_ru_users_for_weekly_top_uploaded_memes():
logger.error(f"Failed to send message to {author_id}: {e}")

await asyncio.sleep(2)


@flow(name="Reward EN users for weekly top uploaded memes")
async def reward_en_users_for_weekly_top_uploaded_memes():
logger = get_run_logger()
logger.info("Going to reward users for weekly top uploaded memes")

uploaded_memes = await get_all_uploaded_memes_weekly_en()
logger.info(f"Received {len(uploaded_memes)} uploaded memes")

if len(uploaded_memes) < 5:
await log("Not enough memes to reward users: only {len(uploaded_memes)}")
return

nuploaded = len(uploaded_memes)
nusers = len(set(m["author_id"] for m in uploaded_memes))
views = sum(m["nmemes_sent"] for m in uploaded_memes)
likes = sum(m["nlikes"] for m in uploaded_memes)
dislikes = sum(m["ndislikes"] for m in uploaded_memes)
avg_like = likes / (likes + dislikes) if likes + dislikes > 0 else 0

logger.info(f"Uploaded: {nuploaded} by {nusers}, views: {views}, like%: {avg_like}")
today = datetime.today().date().strftime("%Y-%m-%d")

###########################
# reward top authors

top_memes = sorted(
uploaded_memes,
key=lambda m: m["nlikes"] / (m["nlikes"] + m["ndislikes"])
if m["nlikes"] + m["ndislikes"] > 0
else 0,
reverse=True,
)[:5]

for i, top_meme in enumerate(top_memes):
if i == 0:
type = TrxType.UPLOADER_TOP_WEEKLY_1
elif i == 1:
type = TrxType.UPLOADER_TOP_WEEKLY_2
elif i == 2:
type = TrxType.UPLOADER_TOP_WEEKLY_3
elif i == 3:
type = TrxType.UPLOADER_TOP_WEEKLY_4
elif i == 4:
type = TrxType.UPLOADER_TOP_WEEKLY_5
else:
continue

await pay_if_not_paid_with_alert(
bot,
top_meme["author_id"],
type,
external_id=today,
)

if top_meme["status"] != MemeStatus.PUBLISHED:
await update_meme(top_meme["meme_id"], status=MemeStatus.PUBLISHED)
await log_meme_sent(top_meme["meme_id"], channel=Channel.TG_CHANNEL_EN)

# send message to tgchannelen

channel_text = f"""
🏆 <code>Best uploaded memes of a week</code>
🥇 - {top_memes[0]["nickname"] or '???'}
🥈 - {top_memes[1]["nickname"] or '???'}
🥉 - {top_memes[2]["nickname"] or '???'}
🏅 - {top_memes[3]["nickname"] or '???'}
🏅 - {top_memes[4]["nickname"] or '???'}
📥 uploaded memes: <b>{nuploaded}</b>
👤 by users: <b>{nusers}</b>
👁️ views: <b>{views}</b>
👍 like %: <b>{round(likes * 100. / (likes + dislikes))}%</b>
Forward top meme to our bot → <a href="https://t.me/ffmemesbot?start=kitchen">win up to 500 🍔</a>
""" # noqa

ms = await bot.send_media_group(
TELEGRAM_CHANNEL_EN_CHAT_ID,
[telegram.InputMediaPhoto(media=m["telegram_file_id"]) for m in top_memes],
caption=channel_text,
parse_mode="HTML",
)

message_link = f"{TELEGRAM_CHANNEL_EN_LINK}/{ms[0].id}"

# send message to authors

author_ids = set(m["author_id"] for m in top_memes)
logger.info(f"Going to notify {len(author_ids)} authors about rewards")
for author_id in author_ids:
user_uploaded_memes = [m for m in uploaded_memes if m["author_id"] == author_id]
likes = sum(m["nlikes"] for m in user_uploaded_memes)
dislikes = sum(m["ndislikes"] for m in user_uploaded_memes)
like_prc = round(likes * 100.0 / (likes + dislikes))
views = sum(m["nmemes_sent"] for m in uploaded_memes)

user_text = f"""
Your stats for uploaded memes:
📥 Uploaded memes: {len(user_uploaded_memes)}
👁️ Views: {views}
👍 Like %: {like_prc}%
Check out top-5 uploaded memes of the week in our channel: {message_link}
"""
try:
await bot.send_message(author_id, user_text)
except Exception as e:
logger.error(f"Failed to send message to {author_id}: {e}")

await asyncio.sleep(2)
3 changes: 1 addition & 2 deletions src/tgbot/handlers/admin/user_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,7 @@ async def handle_show_user_info(
await calculate_inviter_stats()

selected_user_info = await update_user_info_cache(selected_user["id"])

report = await get_user_stats_report(selected_user_info["id"])
report = await get_user_stats_report(selected_user["id"])

await update.message.reply_text(
f"""
Expand Down

0 comments on commit 54bd1af

Please sign in to comment.