forked from jartigag/AoC-Bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
175 lines (134 loc) · 7.79 KB
/
bot.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import collections
from dotenv import dotenv_values
import datetime
import json
import requests
from datetime import datetime as dt
import math
from functools import cmp_to_key
from random import random
from telegram.ext import *
from telegram import Update
config = dotenv_values('.env')
def get_stars(year=dt.now().year):
url = config['URL'].format(YEAR=year, LEADERBOARD=config['LEADERBOARD'])
cookies = dict(session=config['COOKIE'])
response = requests.get(url, cookies=cookies)
if response.status_code != 200:
raise ValueError
members = json.loads(response.text)['members'].values()
stars = collections.defaultdict(list)
for member in members:
stars[member['stars']].append(member['name'])
stars = sorted(stars.items(), reverse=True)
return stars
def get_leaderboard(year=dt.now().year):
url = config['URL'].format(YEAR=year, LEADERBOARD=config['LEADERBOARD'])
cookies = {'session': config['COOKIE']}
stars = collections.defaultdict(list)
response = requests.get(url, cookies=cookies)
if response.status_code != 200: raise ValueError
members = json.loads(response.text)['members'].values()
for member in members: stars[member['local_score']].append(member['name'])
return sorted(stars.items(), reverse=True)
def stars_cmp(p1, p2):
if p1[0] == p2[0] and p1[1] == p2[1]: return 0
if p1[0] == p2[0]: return (1 if p1[1] < p2[1] else -1)
return (1 if p1[0] < p2[1] else -1)
def get_day_completion(year=dt.now().year, day=str(dt.now().day)):
url = config['URL'].format(YEAR=year, LEADERBOARD=config['LEADERBOARD'])
cookies = {'session': config['COOKIE']}
response = requests.get(url, cookies=cookies)
if response.status_code != 200: raise ValueError
members = json.loads(response.text)['members']
get_resolution_ts = lambda day_level: (day_level.get('1', {}).get('get_star_ts', math.inf), day_level.get('2', {}).get('get_star_ts', math.inf))
resolution_ts = {m['name']: get_resolution_ts(m['completion_day_level'][day]) for m in members.values() if day in m['completion_day_level']}
return sorted(resolution_ts.items(), key=cmp_to_key(lambda item1, item2: stars_cmp(item1[1], item2[1])), reverse=True)
async def cat(update: Update, context: CallbackContext) -> None:
cat = requests.get(
'https://mastodon.social/api/v1/timelines/tag/:catsofmastodon',
headers={"Authorization": f"Bearer {config['TOKEN_MASTODON']}"},
).json()
rnd = round( (len(cat)-1)*random() )
await update.message.reply_photo(cat[rnd]['media_attachments'][0]['url'])
async def drink(update: Update, context: CallbackContext) -> None:
cocktail = requests.get('https://www.thecocktaildb.com/api/json/v1/1/random.php').json()
drink = cocktail['drinks'][0]['strDrink']
drink_photo = cocktail['drinks'][0]['strDrinkThumb']
await update.message.reply_photo(drink_photo, caption=drink)
async def dog(update: Update, context: CallbackContext) -> None:
dog = requests.get('https://dog.ceo/api/breeds/image/random').json()
await update.message.reply_photo(dog['message'])
async def duck(update: Update, context: CallbackContext) -> None:
duck = requests.get('https://random-d.uk/api/quack').json()
await update.message.reply_photo(duck['url'])
async def help(update: Update, context: CallbackContext) -> None:
response = 'Los comandos son:\n'
response += '**{command}** - Dame gatitos! 🐈\n'.format(command='/cat')
response += '**{command}** - Dame alcohol! 🍹\n'.format(command='/drink')
response += '**{command}** - Dame perritos! 🐕\n'.format(command='/dog')
response += '**{command}** - Dame patitos! 🦆\n'.format(command='/duck')
response += '**{command}** - Pong! 🏓\n'.format(command='/ping')
response += '**{command}** - Dame estrellitas! ⭐\n'.format(command='/scores')
response += '**{command}** - Dame estrellitas! ⭐\n'.format(command='/leaderboard')
response += '**{command}** - Dame estrellitas! ⭐\n'.format(command='/resolved')
response += '**{command}** - Donde está el repo?\n'.format(command='/repo')
await update.message.reply_text(response, parse_mode='Markdown')
async def notify(context: CallbackContext) -> None:
day = datetime.datetime.today().day
text = 'Bueeeenos días! Traigo [el reto de hoy día {DAY}]({URL}). Al lío!'.format(DAY=day, URL=config['PUZZLE'].format(DAY=day))
print(text)
await context.bot.send_message(chat_id=config['CHAT_ID'], text=text, parse_mode='Markdown')
async def ping(update: Update, context: CallbackContext) -> None:
await update.message.reply_text('Pong 🏓')
async def scores(update: Update, context: CallbackContext) -> None:
year = dt.now().year
if context.args:
year = context.args[0]
try:
stars = get_stars(year)
text = '[tlmn00bs {YEAR} leaderboard]({URL})\n'.format(YEAR=year, URL=config['URL'].format(YEAR=year, LEADERBOARD=config['LEADERBOARD']).replace('.json', '?order=stars'))
for score, names in stars:
text += '**{0:02}** ⭐ {1}\n'.format(score, ', '.join(names))
except ValueError:
text = 'No se pudo obtener el leaderboard 😞'
await update.message.reply_text(text, parse_mode='Markdown')
async def leaderboard(update: Update, context: CallbackContext) -> None:
year = context.args[0] if context.args else dt.now().year
try:
stars = get_leaderboard(year)
url = config["URL"].format(YEAR=year, LEADERBOARD=config['LEADERBOARD']).replace('.json', '?order=stars')
text = '\n'.join([f'[tlmn00bs {year} leaderboard]({url})'] + [f'**{score:02}** ⭐ {", ".join(names)}' for score, names in stars])
except ValueError:
text = 'No se pudo obtener el leaderboard 😞'
await update.message.reply_text(text, parse_mode = 'Markdown')
async def resolved(update: Update, context: CallbackContext) -> None:
year = context.args[0] if context.args else dt.now().year
day = context.args[1] if context.args and len(context.args) > 1 else str(dt.now().day)
leaderboard_text = lambda ordered_rank: [f'{"⭐" * sum(1 for ts in res_ts if ts is not math.inf)} {name}' for name, res_ts in ordered_rank] if len(ordered_rank) > 0 else ['Nadie ha conseguido estrellitas 😢']
try:
ordered_rank = get_day_completion(year, day)
url = config["URL"].format(YEAR=year, LEADERBOARD=config['LEADERBOARD']).replace('.json', '?order=stars')
text = '\n'.join([f'[tlmn00bs {year} leaderboard]({url})'] + leaderboard_text(ordered_rank))
except ValueError:
text = 'No se pudo obtener el leaderboard 😞'
await update.message.reply_text(text, parse_mode = 'Markdown')
async def repo(update: Update, context: CallbackContext) -> None:
await update.message.reply_text('[https://github.com/TLMn00bs/advent-of-code](https://github.com/TLMn00bs/advent-of-code)', parse_mode = 'Markdown')
def main() -> None:
application = Application.builder().token(config['TOKEN']).build()
application.add_handler(CommandHandler('cat', cat))
application.add_handler(CommandHandler('drink', drink))
application.add_handler(CommandHandler('dog', dog))
application.add_handler(CommandHandler('duck', duck))
application.add_handler(CommandHandler('help', help))
application.add_handler(CommandHandler('ping', ping))
application.add_handler(CommandHandler('scores', scores))
application.add_handler(CommandHandler('leaderboard', leaderboard))
application.add_handler(CommandHandler('resolved', resolved))
application.add_handler(CommandHandler('repo', repo))
job = application.job_queue
job.run_repeating(notify, interval=86400, first=datetime.datetime(year=dt.now().year, month=12, day=1, hour=5, minute=00), last=datetime.datetime(year=dt.now().year, month=12, day=25, hour=5, minute=00))
application.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == "__main__":
main()