-
Notifications
You must be signed in to change notification settings - Fork 1
/
user_of_the_day.py
109 lines (81 loc) · 3.45 KB
/
user_of_the_day.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import logging
import os
import random
import datetime
from time import sleep
import psycopg2
import pytz
from telegram.ext import CallbackContext, Updater
# Enable logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
logger = logging.getLogger(__name__)
DATABASE_URL = os.environ['DATABASE_URL']
LIVE_MODE = True
def send_update(context: CallbackContext):
user_list = ['Dave', 'Erik', 'Graham', 'Josh', 'Peter']
user_of_the_day = random.choice(user_list)
record_win(user_of_the_day)
win_percentage = get_win_percentage(username=user_of_the_day)
recent_winners = get_recent_winners()
remaining_users = [user for user in user_list if user != user_of_the_day]
loser_of_the_day = random.choice(remaining_users)
winner_emojis = ['🥇','🏆','🏅','🎉','🎊','🎁','💪','👏','👯','⭐️','🎯']
winner_emoji = random.choice(winner_emojis)
loser_phrases = ['💩 The loser of the day is', '🤡 The clown of the day is',
'🧌 The troll of the day is', '🗞️ The old newz of the day is',
'🐽 The pig of the day is', '🙍♀️ The debbie downer of the day is',
'🪳 The cockroach of the day is',
'🤦♂️ The facepalm of the day is', '🫃 The pregnant man of the day is',
'👎🏻 Thumbs down,']
loser_phrase = f"{random.choice(loser_phrases)} {loser_of_the_day}"
info = f"""{winner_emoji} User of the day is {user_of_the_day} ({win_percentage})!
Recent champs: {recent_winners}
{loser_phrase}.
"""
logger.info(info)
if LIVE_MODE:
context.bot.send_message(chat_id=os.getenv('CHANNEL_ID'), text=info)
def record_win(username):
conn = psycopg2.connect(DATABASE_URL)
cur = conn.cursor()
cur.execute("update user_wins set wins = wins + 1 where username = %s", (username,))
today_pacific = datetime.date.today() - datetime.timedelta(days=1)
cur.execute("insert into user_wins_by_date(win_date, username) values(%s, %s)",
(today_pacific, username,))
conn.commit()
cur.close()
conn.close()
def get_win_percentage(username):
conn = psycopg2.connect(DATABASE_URL)
cur = conn.cursor()
cur.execute("select sum(wins) from user_wins")
total_wins = int(cur.fetchone()[0])
cur.execute("select wins from user_wins where username = %s", (username,))
user_wins = int(cur.fetchone()[0])
cur.close()
conn.close()
return ("{:#.3g}".format(user_wins/total_wins).lstrip("0"))
def get_recent_winners() -> str:
conn = psycopg2.connect(DATABASE_URL)
cur = conn.cursor()
cur.execute("select count(*),username from user_wins_by_date "
"where win_date >= current_date - interval '10' day group by username")
tup = cur.fetchall()
recent_winners = ', '.join([f"{t[1]} ({t[0]})" for t in tup])
cur.close()
conn.close()
return recent_winners
def main() -> None:
# wait a bit so previous instance has a chance to shut down, to avoid Telegram duplicate errors
sleep(60)
token = os.getenv('TOKEN')
updater = Updater(token, use_context=True)
job_queue = updater.job_queue
job_queue.run_daily(send_update, datetime.time(hour=21, minute=0, tzinfo=pytz.timezone('US/Pacific')))
# job_queue.run_repeating(send_update, first=10, interval=60)
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()