Beispiel #1
0
def location(e):
    if e.message and e.message.location:
        u = utils.load_user(e.message.from_user.to_dict())
        u.update(e.message.location.to_dict())
        e.message.reply_text('Nova posição salva')
    elif e.edited_message and e.edited_message.location:
        u = utils.load_user(e.edited_message.from_user.to_dict())
        u.update(e.edited_message.location.to_dict())
    else:
        return False
    utils.save_user(u)
    return True
Beispiel #2
0
 def get_log(self, date):
     """Парсинг json и сохранение данных логов и пользователей в БД"""
     data = self.get_json()
     if 'error' in data:
         logger.debug(data['error'])
     if 'logs' in data:
         # Получение всех логов с форматированным временем
         all_logs = list(correct_time(data['logs']))
         sort_by_created_at(all_logs)
         for log in all_logs:
             first_name = log['first_name']
             second_name = log['second_name']
             user_id = log['user_id']
             message = log['message']
             created_at = log['created_at']
             save_user(first_name, second_name, user_id)
             save_log(message, created_at, user_id)
         logger.info(f'Запись завершена')
Beispiel #3
0
def help(evt, b):
    if evt.message and evt.message.text:
        if evt.message.text == '/sair':
            u = utils.load_user(e.message.from_user)
            if 'latitude' in u:
                del u['latitude']
                utils.save_user(u)
            evt.message.reply_text(text='Bye bye')
        else:
            evt.message.reply_text(
                text='''Esse bot aceita os seguintes exemplos de comandos:
- Enviar sua localização
- Compartilhar sua localização
- <pre>2000</pre> 
- /2000
- <pre>90%</pre>
- /filtro
- /Aron_set
- /sair
''',
                parse_mode='html')
        return True
    return False
Beispiel #4
0
                    help='Telegram username')
parser.add_argument('--email',
                    type=str,
                    default=None,
                    help='Gravatar email address')

if __name__ == '__main__':
    args = parser.parse_args()
    if args.command == 'setup_db':
        db_setup(settings)
    elif args.command == 'populate_data':
        populate_dummy_history(settings,
                               date_range=args.range,
                               username=args.username)
    elif args.command == 'add_user':
        if not args.chat_id:
            print("Please, provide chat_id for the user!")
            sys.exit(1)
        if not args.username:
            print("Please, provide username for the user!")
            sys.exit(1)
        if not args.email:
            print("Please, provide email for the user!")
            sys.exit(1)
        if not save_user(settings,
                         chat_id=args.chat_id,
                         username=args.username,
                         email=args.email):
            print("User {} already exists in database!".format(args.chat_id))
            sys.exit(1)
    	csvreader = csv.reader(f, delimiter=' ')
    	for i, row in enumerate(csvreader):
    		users.append(row[0])

    while(True): 
        try:
        	if(function == 'fetch'):
        		# Get neighbours of each user in the list
        		for i, user in enumerate(users):
        			print('\n', i, user)
        			user_obj = api.get_user(user) 
        			n = fetch_neighbours(user_obj.id, api, direction=direction, force=force)
        			print("neighbours: ", n)

        			# Save user info and the id-screen_name pair since we have it already
        			utils.save_user(user_obj)
        			utils.save_screen_name(user_obj.id, user)

	        if(function == 'make_similarity'):
	        	print("Creating similarity matrix")
	        	fout = 'similarity' + '_' + file.split('.')[0] + '_' + direction + '.csv'
	        	make_similarity_matrix(users, direction = direction, file = fout)

	        if(function == 'make_adjacency'):
	        	print("Creating adjacency matrix")
	        	fout = 'adjacency' + '-' + file.split('.')[0] + '_' + direction + '.csv'
	        	make_adjacency_matrix(users, direction = direction, file = fout)
        	
        	break

        except TweepError as e:
Beispiel #6
0
def filter(evt, b):
    if evt.message and evt.message.text:
        t, m = evt.message.text, evt.message
    elif evt.callback_query and evt.callback_query.data:
        t, m = evt.callback_query.data, evt.callback_query
    else:
        return None
    u = utils.load_user(m.from_user.to_dict())
    c = re.compile('^/([^_]*)_([0-9]+)?%$').match(
        '/Padrao_' + t if re.compile('^[0-9]+%$').match(t) else t)
    if c:
        p, i = c.groups()
        if i is None:
            u['ifilter'].pop(p, None)
        else:
            u['ifilter'][p] = i
    else:
        c = re.compile('^/([^_]*)_([0-9]+)?$').match(
            '/Padrao_' + t if re.compile('^[0-9]+$').match(t) else t)
        if c:
            p, d = c.groups()
            if (d is None) and (p in u['filter']):
                u['filter'].pop(p, None)
            else:
                u['filter'][p] = d
        else:
            c = re.compile('^/([^_]+)_(m|set|reset)$').match(t)
            if c:
                p = c.group(1)
                if c.group(2) == 'reset':
                    if p == 'Padrao':
                        u['filter'][p] = '2000'
                        u['ifilter'][p] = '90'
                    else:
                        u['filter'].pop(p, None)
                        u['ifilter'].pop(p, None)
            else:
                return None
    d, i = u['filter'].get(p), u['ifilter'].get(p)
    k = [[]]
    if d == '0':
        t, d = '%s:\nalerta desativado' % (p, ), u['filter']['Padrao']
        k[0].append(IB("Ativar", callback_data='/%s_' % (p, )))
    else:
        if d is None:
            d = u['filter']['Padrao']
            t = '%s:\ndistância padrão: %sm' % (p, d)
        else:
            t = '%s:\ndistancia máxima: %sm' % (p, d)
            k[0].append(IB("Padrao", callback_data='/%s_' % (p, )))
        if p != 'Padrao':
            k[0].append(IB("Desativar", callback_data='/%s_0' % (p, )))
        k.append([])
        if p != p.upper():
            if i is None:
                t += '\nIV minimo padrão: %s%%' % (u['ifilter'].get(
                    'Padrao', '90'), )
            else:
                t += '\nIV mínimo custom: %s%%' % (i, )
                k[1].append(IB("Padrão", callback_data='/%s_%%' % (p, )))
            for j in ['0', '80', '90', '95', '97', '100']:
                if j != i:
                    k[1].append(
                        IB("%s%%" % (j, ), callback_data='/%s_%s%%' % (p, j)))

    d = max(50, float(d))
    d1, d2 = dec(d), inc(d)
    k[0].append(IB(d1 + "m", callback_data='/%s_%s' % (p, d1)))
    k[0].append(IB(d2 + "m", callback_data='/%s_%s' % (p, d2)))

    if isinstance(m, telegram.callbackquery.CallbackQuery):
        m.answer()
        try:
            u['filter_msg'] = m.edit_message_text(
                t, reply_markup=InlineKeyboardMarkup(k)).to_dict()
        except:
            pass
    else:
        try:
            if 'filter_msg' in u:  # clear button of old msg
                b.edit_message_reply_markup(
                    chat_id=u['filter_msg']['chat']['id'],
                    message_id=u['filter_msg']['message_id'])
                del u['filter_msg']
        except:
            pass
        u['filter_msg'] = m.reply_text(
            text=t, reply_markup=InlineKeyboardMarkup(k)).to_dict()
    print(u)
    return utils.save_user(u)
Beispiel #7
0
    while (True):
        try:
            if (function == 'fetch'):
                # Get neighbours of each user in the list
                for i, user in enumerate(users):
                    print('\n', i, user)
                    user_obj = api.get_user(user)
                    n = fetch_neighbours(user_obj.id,
                                         api,
                                         direction=direction,
                                         force=force)
                    print("neighbours: ", n)

                    # Save user info and the id-screen_name pair since we have it already
                    utils.save_user(user_obj)
                    utils.save_screen_name(user_obj.id, user)

            if (function == 'make_similarity'):
                print("Creating similarity matrix")
                fout = 'similarity' + '_' + file.split(
                    '.')[0] + '_' + direction + '.csv'
                make_similarity_matrix(users, direction=direction, file=fout)

            if (function == 'make_adjacency'):
                print("Creating adjacency matrix")
                fout = 'adjacency' + '-' + file.split(
                    '.')[0] + '_' + direction + '.csv'
                make_adjacency_matrix(users, direction=direction, file=fout)

            break