def sync(message): id = message.chat.id if (message.chat.type == 'group'): send_message( id, 'Эта команда не может быть выполнена в групповых чатах в целях безопасности ваших данных' ) else: connection = data.create_connection(dbname) elems = data.execute_read_query(connection, keys_handler.select_keys(id)) if elems == []: send_message(id, 'Вы не добавили api ключи. Посмотрите /help') else: open, secret = elems[0] handles, status = cf.get_friends(open, secret) if handles is None: if 'Incorrect API key' in status: send_message(id, 'Вы указали неправильные ключи') else: send_message( id, 'Что-то пошло не так. Скорее всего, codeforces сейчас недоступен.' ) logger.critical(status) else: send_message( id, util.__add_handles(id, list(map(lambda x: x.lower(), handles)), handles, connection)) connection.close()
def get_contestants(id): try: resp = requests.get( 'https://codeforces.com/api/contest.ratingChanges?contestId={0}'. format(id)).json() except Exception as e: logger.critical(str(e)) return (None, None) if resp['status'] == 'FAILED': logger.critical(resp['comment']) return (None, None) else: res = dict() for i in range(len(resp['result'])): res[resp['result'][i]['handle']] = \ (resp['result'][i]['oldRating'], resp['result'][i]['newRating']) return (res, resp['result'][0]['contestName'])
def _filter_incidents(filter_=None, include_hosts=True): host_cache = {} keys = redis.zrangebyscore(KEY_INCIDENTS, '-inf', '+inf') incidents = [] for key in keys: incident = redis.hgetall(key) try: if not filter_(incident): continue if include_hosts: if not host_cache.has_key(incident['node_id']): host_cache[incident['node_id']] = \ redis.hgetall(KEY_DEVICE+get_device_id_hash(incident['node_id'])) incident['host'] = host_cache[incident['node_id']] incidents.append(jsonify_incident(key, incident)) except Exception as e: logger.critical(e) return incidents
def get_category_info(_url): """ 获取产品信息 :param _url: 综合查询链接 :return: category_info_list: [[category_name, api], [], ...] """ category_info_list = [] response = requests.get(_url, headers=headers) html = response.text if not html: logger.critical('{}请求失败,请手动检查是否要登录'.format(_url)) sys.exit() tree = get_tree(html) xpath_expr = '//a[@class="cat-name fst-cat-name"]' result = tree.xpath(xpath_expr) if not result: logger.critical('在按综合查询页面没有找到产品') logger.critical('请手动检查网址是否错误,{}'.format(_url)) sys.exit() for _ in result: category_name = _.xpath('text()') category_api = _.xpath('@href') if not category_name or not category_api: continue name = category_name[0] api = category_api[0] if name == '服装' or name == '所有宝贝': continue category_info_list.append([name, api]) return category_info_list
def get_ratings(handles): query = '' for handle in handles: query += handle[0] query += ';' try: resp = requests.get( 'https://codeforces.com/api/user.info?handles={0}'.format( query)).json() except Exception as e: logger.critical(str(e)) return None if resp['status'] == 'FAILED': logger.critical(resp['comment']) return None else: res = dict() for i in range(len(handles)): res[handles[i]] = resp['result'][i]['rating'] return res
def check_users(handles): url = 'https://codeforces.com/api/user.info?handles=' for handle in handles: url += handle url += ';' try: resp = requests.get(url).json() except Exception as e: logger.critical(str(e)) return (-1, None) if resp['status'] == 'OK': handles = list() for x in resp['result']: handles.append(x['handle']) return (1, handles) elif resp['comment'].startswith('handles: User with handle') and resp[ 'comment'].endswith('not found'): s = resp['comment'] return (0, s[s.find('handle ') + 7:s.find('not') - 1]) else: logger.critical(resp['comment']) return (-1, None)
def check_changes(): try: resp = requests.get( 'https://codeforces.com/api/contest.list?gym=false').json() except Exception as e: logger.critical(str(e)) return list() if resp['status'] == 'FAILED': logger.critical(resp['comment']) return list() res = list() connection = data.create_connection(dbname) i = 0 while resp['result'][i]['relativeTimeSeconds'] < maxTime: id = resp['result'][i]['id'] if resp['result'][i]['phase'] != 'FINISHED' or \ data.execute_read_query(connection, contests_handler.select_id(id)) != []: i += 1 continue try: resp2 = requests.get( 'https://codeforces.com/api/contest.ratingChanges?contestId={0}' .format(id)).json() except Exception as e: logger.critical(str(e)) i += 1 continue logger.debug('i = {0}; id = {1};'.format(i, id)) if resp2['status'] == 'OK' and resp2['result'] != []: res.append(id) data.execute_query(connection, contests_handler.insert_id(id)) i += 1 connection.close() logger.debug('found {0}'.format(res)) return res
from var import interval import cf import commands def watch_changes(): while True: contests = cf.check_changes() for id in contests: send_everyone(id) sleep(interval) # main try: thread1 = Thread(target=Bot.infinity_polling) thread2 = Thread(target=watch_changes) thread1.daemon = True thread2.daemon = True thread1.start() thread2.start() logger.debug('started') while True: sleep(100) except (KeyboardInterrupt, SystemExit): print('\b \b\b \binterrupted') logger.debug('interrupted') except Exception as e: logger.critical(str(e))