def on_data(self, data): if self.counter <= self.max_tweets: mongo() tweet = json.loads(data) tweets.insert(tweet) self.counter += 1 else: tweetStream.disconnect() print("Max Limit Reached: Disconnecting.........")
def buscar(lon,lat,rad): #client = MongoClient('mongodb://*****:*****@ds015953.mlab.com:15953/code101') #collection=client.code101.docs101 client=mongo() res=client.mostrar_todos(float(lon),float(lat),float(rad)) #if res.count()==0: ret = json_util.dumps({'rooms': res}, default=json_util.default) #else: '''coord=[] for i in range(res.count()): coor1=str(res[i]['Coord']['coordinates'][0]) coor2=str(res[i]['Coord']['coordinates'][1]) i+=1 aux={'coor':[coor1,coor2]} coord.append(aux)''' # ret = json_util.dumps({'rooms': res}, default=json_util.default) return Response(response=ret, status=200, headers=None, content_type='application/json', direct_passthrough=False)
def new_cuarto(): if request.method == 'POST': if request.headers['Content-Type'] == 'application/json': #client = MongoClient('mongodb://*****:*****@ds015953.mlab.com:15953/code101') #collection=client.code101.docs101 client=mongo() try: data = json.loads(request.data) except (ValueError, KeyError, TypeError): # Not valid information, bail out and return an error return jsonify({'status': 'error'}) #collection.insert({"name": data['name'], "handle": data['handle'] }) #print collection.count() if client.insert_cuarto_usuario(str(data['nombre']),str(data['direc']),str(data['email']),int(data['fono']),[float(data['coord0']),float(data['coord1'])],int(data['precio']),str(data['genero']),[str(data['serv0']),str(data['serv1']),str(data['serv2']),str(data['serv3']),str(data['serv4'])],str(data['imagen']))==True: '''ret=jsonify({'status': 'successful'}) return Response(response=ret, status=200, headers=None, content_type='application/json', direct_passthrough=False)''' return jsonify({'status': 'successful'}) return jsonify({'status': 'error'}) else: return jsonify({'status': 'error'}) else: return jsonify({'status': 'error'})
def reg(id): client=mongo() res=client.busq_id(id) ret=json_util.dumps({'rooms':res}, default=json_util.default) return Response(response=ret, status=200, headers=None, content_type='application/json', direct_passthrough=False)
def init_mongo(uri): # init mongo es_conn = mongo.mongo(uri) try: es_conn.info() except mongo.ConnectionError: raise mongoConnectionError(uri) return es_conn
def show_feed(): while 1: mongo() it = tweets.find() for i in it: try: global sentim global subob sent = TextBlob(i['text']) (senti, subob) = sent.sentiment if subob <= 0.5: subobr = "Objective Statement" else: subobr = "Subjective Statement" if senti <= (-0.1): sentim = "Negative Sentiment" elif senti > (-0.1) and senti <= 0.1: sentim = "Neutral Sentiment" else: setim = "Positive Sentiment" print("\n\n") print("Tweet::") print i['text'] print("Screen Name: " + i['user']['screen_name']) print("User Name: " + i['user']['name']) print("Created on: " + i['created_at']) print("language: " + i['lang']) print("Sentiment: " + sentim) print("Subjective/Objective: " + subobr) except KeyboardInterrupt: #Handles Keybooad interrupt | did not check | Might be a bug return except: continue
def buscar_cuarto(lon,lat,rad,gen,p_min,p_max,wifi,pet,tv,agua,toilet): #client = MongoClient('mongodb://*****:*****@ds015953.mlab.com:15953/code101') #collection=client.code101.docs101 client=mongo() res=client.mas_baratos(float(lon),float(lat),float(rad),gen,[toilet,tv,agua,wifi,pet],int(p_min),int(p_max)) ret = json_util.dumps({'rooms': res}, default=json_util.default) return Response(response=ret, status=200, headers=None, content_type='application/json', direct_passthrough=False)
def buscar2(lon1,lat1,lon2,lat2): #client = MongoClient('mongodb://*****:*****@ds015953.mlab.com:15953/code101') #collection=client.code101.docs101 client=mongo() res=client.mostrar_todos2(float(lon1),float(lat1),float(lon2),float(lat2)) ret = json_util.dumps({'rooms': res}, default=json_util.default) return Response(response=ret, status=200, headers=None, content_type='application/json', direct_passthrough=False)
def test(): ''' After connecting to the database, data of type int, float and string are first generated and displayed, then filtered and displayed, and finally the data in the database is deleted ''' zB = mongo() zB.get_Data(int, (1, 50), 8) zB.get_Data(float, (1, 100), 5, 1) zB.get_Data(str, string.ascii_letters + string.digits + "@#$!", 10, 5) zB.find_many() zB.screen_Data(int, (16, 61)) zB.screen_Data(float, (3.14, 52.0)) zB.screen_Data(str, 'a', 'b', 'c') zB.find_many() zB.delete_mycol()
import sys, threading, time, os, datetime, time, inspect, subprocess, socket from subprocess import PIPE, STDOUT import json from audio.audio import Audio from video.video import Video from datetime import datetime import signal from mongo import mongo from bson.objectid import ObjectId config = None if os.path.exists(os.path.join(os.getcwd(), "config.json")): f = open(os.path.join(os.getcwd(), "config.json"), ) config = json.load(f) mg = mongo(host=config["host_db"], port=config["port_db"]) ip_server = config["host"] # IP DEL SERIVIDOR portAudio = config["port_audio"] # PUERTO DE AUDIO port1 = config["port_video1"] # PUERTO DE VIDEO 1 port2 = config["port_video2"] # PUERTO DE VIDEO 2 port3 = config["port_video3"] # PUERTO DE VIDEO 3 port4 = config["port_video4"] # PUERTO DE VIDEO 4 # ------------------ terrible daemon code for windows ------------------- if __name__ == '__main__': Windows = sys.platform == 'win32' ProcessFileName = os.path.realpath(__file__) pidName = ProcessFileName.split('\\')[-1].replace('.py', '') if Windows:
import threading import logging from audio.audio import Audio from video.video import Video from datetime import datetime import os import keyboard from video.OpenPoseClassPython import OPVideo from pynput import keyboard as kb import socket from mongo import mongo mg = mongo() class actividad: def __init__(self, root): t = datetime.now() self.data = { "root": root, "audioFile": root + "/audio.wav", "video1File": root + "/video1.avi", "video2File": root + "/video2.avi", "video3File": root + "/video3.avi", "video4File": root + "/video4.avi", "videoout1File": root + "/videoout1.avi", "videoout2File": root + "/videoout2.avi", "videoout3File": root + "/videoout3.avi", "videoout4File": root + "/videoout4.avi", "creationTime": datetime.today(), "startRecording": "", "endRecording": ""
from flask import Flask from flask import render_template from flask import request from flask import url_for, redirect, flash import mongo app = Flask(__name__) app.secret_key = "super_secret" m = mongo.mongo() @app.route("/", methods=["GET", "POST"]) def default(): stories = mongo.mongo.getStories(m) if request.method == "GET": return render_template("default.html", stories=stories) if request.method == "POST": ns = str(request.form["newStory"]) b = request.form["button"] if b == "Choose Story": storytitle = str(request.form["menu"]) # lines = mongo.mongo.getLines(storytitle) return render_template("story.html", storytitle=storytitle) elif b == "Create Story": if not ns: stories = mongo.mongo.getStories(m) return render_template("default.html", stories=stories) else: mongo.mongo.newStory(m, ns) stories = mongo.mongo.getStories(m)
def __init__(self): self.mongo = mongo()
def __init__(self): self.bot = telebot.TeleBot(ShedulerToken.token) self.mongo = mongo.mongo() self.threadTimer = Thread(target=self.send_message, args=("Напоминание!", )) for men in self.mongo.coll.find(): print(men) # удаляем все документы коллекции #self.mongo.coll.remove({}) # Помощь @self.bot.message_handler(commands=['help']) def help(message): self.menu_clear(message.chat.id) _str = '' _str += '/help - помощь\n' _str += '/start - начать работу\n' _str += '/add name_event time text - добавить напоминание. Формат времени 16:00\n' _str += '/on name_event - включить напоминание\n' _str += '/on name_event date_number - включить напоминание в дни недели\n' _str += '/off name_event - отключить напоминание\n' _str += '/off name_event date_number - выключить напоминание в дни недели\n' _str += '/events - список напоминаний\n' _str += '/geo - взять локацию, для уточнения времени\n' _str += '\n' _str += '/menu - версия с кнопками управления\n' self.bot.send_message(message.chat.id, _str) # Регистрация в системе @self.bot.message_handler(commands=['start']) def get_start(message): self.menu_clear(message.chat.id) print('start', message.chat.id) if not self.mongo.coll.find({"id": message.chat.id}).count(): self.bot.send_message(message.chat.id, 'Добро пожаловать! Я бот напоминалка.') self.bot.send_message(message.chat.id, 'Для помощи используй /help') self.new(message) #else : # self.bot.send_message(message.chat.id, 'Ты уже подключен.') # for men in self.mongo.coll.find({"id": message.chat.id}): # if not men.get('timezone_offset', None) : # self.geoGet(message) # Добавить напоминание @self.bot.message_handler(commands=['add']) def get_add(message): self.menu_clear(message.chat.id) print('add', message.chat.id) if not self.mongo.coll.find({"id": message.chat.id}).count(): self.new(message) args = message.text.split(' ') print(len(args)) if len(args) <= 3: self.bot.send_message( message.chat.id, 'Формат команды: /add имя_события время(14:15) напоминание' ) else: text = '' for i in range(len(args) - 3): text += args[i + 3] + ' ' name = args[1] time = args[2] # Добавляем новое напоминание. self.add(message.chat.id, name, time, text, self.event_new['days']) print(self.mongo.coll.find({"id": message.chat.id}).count()) for men in self.mongo.coll.find({"id": message.chat.id}): print(men) # Включаем напоминание по имени. @self.bot.message_handler(commands=['on']) def get_on(message): self.menu_clear(message.chat.id) print('on', message.chat.id) if not self.mongo.coll.find({"id": message.chat.id}).count(): self.bot.send_message(message.chat.id, 'Вы не зарегистрированы.') return args = message.text.split(' ') print(len(args)) if len(args) <= 1: self.bot.send_message(message.chat.id, 'Формат команды: /on имя_события') elif len(args) <= 2: name = args[1] self.days_on(message.chat.id, name) else: name = args[1] for i in range(len(args) - 2): self.day_on(message.chat.id, name, args[i + 2]) # Выключаем напоминание по имени. @self.bot.message_handler(commands=['off']) def get_off(message): self.menu_clear(message.chat.id) print('off', message.chat.id) if not self.mongo.coll.find({"id": message.chat.id}).count(): self.bot.send_message(message.chat.id, 'Вы не зарегистрированы.') return args = message.text.split(' ') print(len(args)) if len(args) <= 1: self.bot.send_message(message.chat.id, 'Формат команды: /off имя_события') elif len(args) <= 2: name = args[1] self.days_off(message.chat.id, name) else: name = args[1] for i in range(len(args) - 2): self.day_off(message.chat.id, name, args[i + 2]) # Список напоминаний пользователя @self.bot.message_handler(commands=['events']) def get_events(message): self.menu_clear(message.chat.id) print('events', message.chat.id) self.events(message) # Удаляем напоминание @self.bot.message_handler(commands=['del']) def get_del(message): self.menu_clear(message.chat.id) print('del', message.chat.id) if not self.mongo.coll.find({"id": message.chat.id}).count(): self.bot.send_message(message.chat.id, 'Вы не зарегистрированы.') return args = message.text.split(' ') print(len(args)) if len(args) <= 1: self.bot.send_message(message.chat.id, 'Формат команды: /off имя_события') else: name = args[1] self.del_event(message, name) # Запрос локации пользователя @self.bot.message_handler(commands=['geo']) def get_geo(message): self.menu_clear(message.chat.id) print('geo', message.chat.id) self.geoGet(message) # Локация пользователя @self.bot.message_handler(content_types=['location']) def get_location(message): print('location', message.chat.id) ## # Берем временную зону пользователя. ## tz = tzwhere.tzwhere() timezone_str = tz.tzNameAt(message.location.latitude, message.location.longitude) timezone = pytz.timezone(timezone_str) #print(timezone, timezone.utcoffset(datetime.datetime.now())) timezone_offset = str(timezone.utcoffset(datetime.datetime.now())) self.mongo.coll.update({"id": message.chat.id}, { "$set": { "latitude": message.location.latitude, "longitude": message.location.longitude, "timezone_offset": timezone_offset } }) self.bot.send_message( message.from_user.id, "Ваше местоположение и временная зона: {} {}".format( timezone_str, timezone_offset)) #for men in self.mongo.coll.find({"id": message.chat.id}): # print(men) @self.bot.message_handler(commands=['days']) def get_days(message): self.menu_clear(message.chat.id) print('days', message.chat.id) if not self.mongo.coll.find({"id": message.chat.id}).count(): self.bot.send_message(message.chat.id, 'Вы не зарегистрированы.') return markup = types.InlineKeyboardMarkup() for men in self.mongo.coll.find({"id": message.chat.id}): events = men.get('events', []) for event in events: button = types.InlineKeyboardButton( text=event['name'], callback_data=json.dumps({ 'id': message.chat.id, 't': 'e' })) markup.add(button) self.bot.send_message(chat_id=message.chat.id, text='Ваши события', reply_markup=markup) @self.bot.message_handler(commands=['menu']) def menu(message): self.menu_clear(message.chat.id) self.menu(message) @self.bot.callback_query_handler(func=lambda call: True) def query_handler(call): print(call.data) data = json.loads(call.data) _id = call.message.chat.id men = self.mongo.coll.find_one({"id": _id}) if not men: return if data['c'] == 'events': self.events(call.message) elif data['c'] == 'new': self.bot.send_message( _id, text='Напишите название нового напоминания') men['event_new']['menu_new_status'] = 'get_name' self.mongo.coll.update( {'id': _id}, {"$set": { 'event_new': men['event_new'] }}) elif data['c'] == 'del': name = data.get('name') if name: self.del_event(call.message, name) self.menu_del(call.message) elif data['c'] == 'menu': self.menu(call.message) elif data['c'] == 'add_day': men['event_new']['days'][ data['day']] = not men['event_new']['days'][data['day']] self.mongo.coll.update( {'id': _id}, {"$set": { 'event_new': men['event_new'] }}) self.add(_id, men['event_new']['name'], men['event_new']['time'], men['event_new']['text'], men['event_new']['days']) self.days(call.message) elif data['c'] == 'change': name = data.get('name') if name: men['event_new']['name'] = name men['event_new']['menu_new_status'] = 'get_time' self.mongo.coll.update( {'id': _id}, {"$set": { 'event_new': men['event_new'] }}) self.bot.send_message( _id, "Введите время напоминания(формат: 17:15)") else: self.menu_change(call.message) elif data['c'] == 'geo': self.menu_clear(_id) print('geo', _id) self.geoGet(call.message) @self.bot.message_handler(content_types=['text']) def get_text(message): print('text', message.chat.id) men = self.mongo.coll.find_one({"id": message.chat.id}) if not men: return menu_new_status = men['event_new'].get('menu_new_status', '') if menu_new_status == 'get_name': men['event_new']['name'] = message.text men['event_new']['menu_new_status'] = 'get_time' self.mongo.coll.update( {'id': message.chat.id}, {"$set": { 'event_new': men['event_new'] }}) self.bot.send_message( message.chat.id, "Введите время напоминания(формат: 17:15)") elif menu_new_status == 'get_time': try: datetime.datetime.strptime(message.text, '%H:%M') men['event_new']['time'] = message.text men['event_new']['menu_new_status'] = 'get_text' self.mongo.coll.update( {'id': message.chat.id}, {"$set": { 'event_new': men['event_new'] }}) self.bot.send_message(message.chat.id, "Напишите текст напоминания") except: self.bot.send_message( message.chat.id, "Время {} некорректно, попробуйте еще раз.".format( message.text)) ''' if re.search(r'^\d{2,2}\:\d{2,2}$', message.text): men['event_new']['time'] = message.text men['event_new']['menu_new_status'] = 'get_text' self.mongo.coll.update({'id': message.chat.id}, {"$set": {'event_new': men['event_new']}}) self.bot.send_message(message.chat.id, "Напишите текст напоминания") else : self.bot.send_message(message.chat.id, "Время {} некорректно".format(message.text)) ''' elif menu_new_status == 'get_text': men['event_new']['text'] = message.text men['event_new']['menu_new_status'] = '' self.mongo.coll.update( {'id': message.chat.id}, {"$set": { 'event_new': men['event_new'] }}) self.add(message.chat.id, men['event_new']['name'], men['event_new']['time'], men['event_new']['text'], men['event_new']['days']) self.days(message) else: self.bot.send_message( message.from_user.id, "Привет {}, используй /help ".format( men.get("first_name", ''))) '''
def connectToDatabase(self): self.connection = mongo() if not self.connection.connected: QMessageBox.critical(self.ui.centralwidget, "Connection to MongoDB", "Connection to database failed. Exiting application.") raise SystemExit('Connection to database failed. Exiting application.')