def contact_del(): log.debug('{}'.format(request.form)) input_user = InputUser(int(request.form['userid']), 0) try: user = client(GetUsersRequest([input_user])) log.debug('{}'.format(user)) if user[0].photo: filename = 'app/contacts/static/tmp/{}.jpg'.format( user[0].photo.photo_id) if Path(filename).is_file(): log.info('Removing profile photo {}_{} to {}'.format( user[0].first_name, user[0].last_name, filename)) os.remove(filename) result = client(DeleteContactRequest(input_user)) log.debug('{}'.format(result)) session['error'] = 'Контакт {}_{} успешно удален.'.format( result.user.first_name, result.user.last_name) except Exception as e: session['error'] = 'Ошибка удаления контакта {}'.format(e) return redirect(url_for('contacts.contact_list'))
def contact_list(): errormsg = '' if 'error' in session: errormsg = session['error'] session.pop('error') users = [] contacts = client(GetContactsRequest(0)) log.debug('{}'.format(contacts)) for user in contacts.users: user_profile = dict() user_profile['id'] = user.id user_profile['access_hash'] = user.access_hash user_profile['first_name'] = user.first_name user_profile['last_name'] = user.last_name user_profile['phone'] = user.phone if user.photo: filename = 'app/contacts/static/tmp/{}.jpg'.format( user.photo.photo_id) if not Path(filename).is_file(): log.info('Downloading profile photo {}_{} to {}'.format( user.first_name, user.last_name, filename)) client.download_profile_photo(user, file=filename) user_profile['photo'] = '{}.jpg'.format(user.photo.photo_id) users.append(user_profile) output = render_template('contact_list.html', contacts=sorted(users, key=lambda k: k['first_name']), errormsg=errormsg) return output
def contact_add(): log.debug('{}'.format(request.form)) first_name = request.form['first_name'] last_name = request.form['last_name'] phone_number = request.form['phone_number'] if request.form['contactChange'] == '1': action = 'изменен' else: action = 'добавлен' log.info('Adding user {}_{} {}'.format(first_name, last_name, phone_number)) input_contact = InputPhoneContact(0, phone_number, first_name, last_name) contact = client(ImportContactsRequest([input_contact])) if contact.users: errormsg = '' log.debug('Contacts found: {}'.format(contact)) for user in contact.users: errormsg += 'Контакт {}_{} ({}) успешно {}'.format( user.first_name, user.last_name, user.phone, action) session['error'] = errormsg else: log.debug('Contacts not found: {}'.format(input_contact)) session['error'] = 'Пользователь {} не найден.'.format(phone_number) return redirect(url_for('contacts.contact_list'))
def POST(self): error = "" webdata = web.input(action="", matchcsv="", matchfile={}) action = webdata.action matchcsv = webdata.matchcsv matchfile = webdata.matchfile date = '' match_id = 0 if action == "uploadmatch": log.info('uploadmatch +', 'Controller') if matchcsv == "" and matchfile != {}: matchcsv = matchfile.value filename = matchfile.filename if 'match' in filename: date = re.findall('([0-9]*-[0-9]*-[0-9]*)', filename)[0] error, match_id = tmatch.parseCsvMatch(matchcsv, date) log.info('uploadmatch -', 'Controller') else: error = "Unknown action" title = "Upload" # Stay on upload page if error if error == "": raise web.seeother('/matches/'+str(match_id)) else: return render.wrap(view.cr_upload(defaultcsv=matchcsv), title=title, error=error)
def read_json_file(path): try: log.info('Reading ' + path + ' file ...') with open(path, 'r') as f: log.info(path + ' file opened.') return json.load(f) except IOError as err: # whatever reader errors you care about log.error('|IOError| - File not found or couldn\'t be open')
def write_json_file(path, content): try: log.info('Opening ' + path + ' file ...') with open(path, 'w') as outfile: json.dump(content, outfile, ensure_ascii=False) log.info(path + ' file writed.') except IOError as err: # whatever reader errors you care about log.error('|IOError| - File not found or couldn\'t be open to write')
def after_request(response): """ Logging after every request. """ # This avoids the duplication of registry in the log, # since that 500 is already logged via @app.errorhandler. log.info('%s %s %s %s %s %s', request.remote_addr, request.method, request.scheme, request.full_path, response.status, response.headers['Content-Length']) return response
def closeMatch(match_id): log.info('closeMatch('+str(match_id)+') +', 'tmatch') players = list(db.query(""" SELECT distinct fs.player_id FROM tframe f, tframescore fs WHERE f.match_id=$match_id AND fs.frame_id=f.frame_id """, vars={'match_id':match_id})) if len(players) != 2: error = "uh oh" return for player in players: player['frames_won'] = list(db.query(""" SELECT count(*) as frames_won FROM tframe f, tframescore fs WHERE f.match_id=$match_id AND fs.frame_id=f.frame_id AND fs.player_id=$player_id AND fs.won=1 """, vars={'match_id':match_id, 'player_id':player['player_id']}))[0]['frames_won'] player['total_points'] = list(db.query(""" SELECT IFNULL(sum(fs.score), 0) as total_points FROM tframescore fs, tframe f WHERE f.match_id=$match_id AND fs.frame_id=f.frame_id AND fs.player_id=$player_id """, vars={'match_id':match_id, 'player_id':player['player_id']}))[0]['total_points'] players[0]['won'] = True # player 0 wins by default if players[1]['frames_won'] > players[0]['frames_won']: players[0]['won'] = False elif players[1]['frames_won'] == players[0]['frames_won']: # Tie, go by aggregate points if players[1]['total_points'] > players[0]['total_points']: players[0]['won'] = False players[1]['won'] = not players[0]['won'] for player in players: createMatchScore(match_id, player['player_id'], player['won'], player['frames_won'], player['total_points']) log.info('closeMatch -', 'tmatch')
def updateElo(winner_id, loser_id, frame_id): winner = getBasicPlayerInfo(winner_id) loser = getBasicPlayerInfo(loser_id) prob = getProbability(winner['elo'], loser['elo']) change = getEloChange(prob) changeElo(winner_id, change, frame_id, loser['elo']) changeElo(loser_id, -change, frame_id, winner['elo']) log.info( winner['name'] + ' elo: ' + str(winner['elo']) + ' + ' + str(change), 'tplayer') log.info( loser['name'] + ' elo: ' + str(loser['elo']) + ' - ' + str(change), 'tplayer')
def contact_list(): errormsg = '' if 'error' in session: errormsg = session['error'] session.pop('error') users = [] contacts = client.send(functions.contacts.GetContacts(0)) log.debug('{}'.format(contacts)) for user in contacts.users: user_profile = dict() user_profile['id'] = user.id user_profile['access_hash'] = user.access_hash user_profile['first_name'] = user.first_name user_profile['last_name'] = user.last_name user_profile['phone'] = user.phone if user.photo: filename = 'app/contacts/static/tmp/{}.jpg'.format( user.photo.photo_id) if not Path(filename).is_file(): log.info('Downloading profile photo {}_{} to {}'.format( user.first_name, user.last_name, filename)) photos = client.get_user_profile_photos(user.id) # log.debug('photos: {}'.format(photos)) for photo in photos: log.debug('Hello') if photo.width == 640: user_profile['photo'] = client.download_media( photo.file_id, file_name='{}.jpg'.format(user.photo.photo_id)) # user_profile['photo'] = '{}.jpg'.format(user.photo.photo_id) users.append(user_profile) # locale.setlocale(locale.LC_ALL, "") # output = render_template('contact_list.html', contacts=sorted(users, key=lambda k: k['first_name']), errormsg=errormsg) # output = render_template('contact_list.html', contacts=sorted(users, key=lambda k: -int(k['first_name'].replace(",", ""))), errormsg=errormsg) # output = render_template('contact_list.html', contacts=users.sort(key='first_name'), errormsg=errormsg) output = render_template('contact_list.html', contacts=users, errormsg=errormsg) return output
from time import strftime from flask import Flask, jsonify, request, redirect, url_for from app.api import telegram from app.contacts import contacts from app.utils import log log.info('Initializing application.') from app.tgclient import client app = Flask(__name__) app.register_blueprint(telegram.bp) app.register_blueprint(contacts.bp) app.secret_key = 'ohgheiphah9shei9Phaetoh9' app.config['SESSION_TYPE'] = 'filesystem' log.info('Application started') @app.route('/') @app.route('/index') def index(): return redirect(url_for('contacts.contact_list'), code=301) @app.route('/help', methods=['GET']) def help(): """Print available functions.""" func_list = {} for rule in app.url_map.iter_rules():
def handle(self, full_command: CommandSchema): self.item_data = item.get_by_priority_and_user_id( db_session=self.db_session, priority=self.priority, user_id=full_command.user_id) if not self.item_data: raise WrongPriorityException log.info("BEFORE") log.info(self.item_data.title) log.info(self.item_data.priority) self.obj = item.update( db_session=self.db_session, db_obj=self.item_data, obj_in=ItemUpdate(title=self.title, priority=self.priority), ) self.db_session.refresh(self.obj) log.info("AFTER") log.info(self.obj.title) log.info(self.item_data.title) log.info(self.obj.priority)
from telethon.tl.functions.users import GetUsersRequest from telethon.tl.types import InputUser from app.utils import log, msglog from app.config import config api_id = config['telethon']['api_id'] api_hash = config['telethon']['api_hash'] if config['proxy']['enabled'] == 'True': proxy_host = config['proxy']['hostname'] proxy_port = config['proxy']['port'] proxy_user = config['proxy']['username'] proxy_pass = config['proxy']['password'] log.info('Initializing conection to telegram with proxy {}'.format( tuple((socks.SOCKS5, proxy_host, proxy_port, True, proxy_user, proxy_pass)))) client = TelegramClient('mainclient', api_id, api_hash, proxy=tuple( (socks.SOCKS5, proxy_host, int(proxy_port), True, proxy_user, proxy_pass)), update_workers=True, spawn_read_thread=True) else: log.info('Initializing conection to telegram') client = TelegramClient('mainclient', api_id, api_hash, update_workers=True,