Skip to content

Instantly share code, notes, and snippets.

@ketankr9
Last active July 23, 2019 07:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ketankr9/274f0ea525058e2e97ca90cd06083074 to your computer and use it in GitHub Desktop.
Save ketankr9/274f0ea525058e2e97ca90cd06083074 to your computer and use it in GitHub Desktop.
Telegram bot which sends the schedule of programming contests held at various hosts.
TOKEN='****DECLARE YOUR TOKEN HERE****'
import time
import random
import telepot
from telepot.loop import MessageLoop
import requests
from datetime import datetime, timezone, date
import pytz
"""
$ pip3 install requests telepot pytz
$ python3 contest_bot.py
"""
data = requests.get(url="https://clist.by/get/events/").json()
def get_update():
refresh_list()
global data
return data
def refresh_list():
global data
data = requests.get(url="https://clist.by/get/events/").json()
def local_time(utc_time):
format = '%Y-%m-%dT%H:%M:%S'
pst = pytz.timezone("Asia/Calcutta")
d = datetime.strptime(utc_time, format) #3.2+
d = d.replace(tzinfo=timezone.utc).astimezone(tz=pst)
return d.strftime("%d-%m %H:%M")
def timedelta(time1, time2=None):
format = '%Y-%m-%dT%H:%M:%S'
pst = pytz.timezone("Asia/Calcutta")
d = datetime.strptime(time1, format) #3.2+
d = d.replace(tzinfo=timezone.utc).astimezone(tz=pst)
if time2 == None:
d2 = datetime.now()
else:
d2 = datetime.strptime(time2, format) #3.2+
d2 = d2.replace(tzinfo=timezone.utc).astimezone(tz=pst)
print(1.0*(d2-d).seconds)
return 1.0*(d2-d).seconds
def get_host(data, hostName):
items = []
all_hosts = ['codeforces.com', 'codechef.com', 'leetcode.com', 'atcoder.jp', 'topcoder.com']
for x in data:
if (hostName == 'all' and (x['host'] in all_hosts )) or x['host'] == hostName:
try:
if (x['host'] == 'topcoder.com' and 'SRM' not in x['title'] and 'TCO' not in x['title']) or timedelta(x['start']) < -10800:
continue
tmp = "["+ x['title'] +"](%s)"%x["url"]
tdelta = timedelta(x["start"], x["end"])
items.append([tmp, ":", local_time(x["start"]), "*%2d:%02d hrs*\t\t\t"%(tdelta/3600, (tdelta/3600 - int(tdelta/3600))*60)] )
except Exception as e:
print("ERROR", e)
return items
def handle_command(command, args):
contests = []
data = get_update()
if command == '/all':
contests = get_host(data, 'all')
elif command in ['/codeforces', '/cf']:
contests = get_host(data, 'codeforces.com')
elif command in ['/codechef', '/cc']:
contests = get_host(data, 'codechef.com')
elif command in ['/leetcode', '/lc']:
contests = get_host(data, 'leetcode.com')
elif command in ['/atcoder', '/at']:
contests = get_host(data, 'atcoder.jp')
elif command in ['/hackerearth', '/he']:
contests = get_host(data, 'hackerearth.com')
elif command in ['/topcoder', '/tc']:
contests = get_host(data, 'topcoder.com')
elif command == '/next':
contests = get_host(data, 'all')
elif command == '/refresh':
refresh_list()
return "Feeling fresh \\*-\\*"
if len(contests) == 0:
return "No contests found"
contests.sort(key=lambda r: datetime.strptime(r[2], "%d-%m %H:%M"))
if command == '/next':
contests = [contests[0]]
reply = "\n----------------------------------------------------\n".join([" ".join([x[0], x[1],"\n_"+x[2]+"_", x[3]]) for x in contests[:20]])
return reply
def handle(msg):
chat_id = msg['chat']['id']
print('Got message: %s' % msg['text'])
if msg['text'][0] == '/':
bot.sendMessage(chat_id, handle_command(msg['text'].split()[0], msg['text'].split()[1:]), parse_mode= 'Markdown')
else:
bot.sendMessage(chat_id, '*_*')
bot = telepot.Bot(TOKEN)
MessageLoop(bot, handle).run_as_thread()
print('I am listening ...')
while 1:
time.sleep(10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment