def call_back(call: telebot.types.CallbackQuery): if call.data == 'invoice': PRICE = telebot.types.LabeledPrice( label='Подписка на iMove: Ukraine на 1 месяц', amount=int(config.SUBS_COST + '99')) bot.send_invoice( chat_id=call.message.chat.id, title='Subscribe [1 month]', description=msg['invoice'], provider_token=config.PAY_TOKEN, currency='EUR', is_flexible= False, # True если конечная цена зависит от способа доставки prices=[PRICE], start_parameter='time-machine-example', invoice_payload='some-invoice-payload-for-our-internal-use') if call.data == 'answer': connection = Db().connect() chat_id = str(call.message.text).split( 'Сообщение от пользователя')[1].split('\n')[0].split('(')[0] question = str(call.message.text).split('\n-----------------\n') msg_id = connection.cursor().execute( 'SELECT id FROM messages WHERE chat_id=? AND message=?', (str(chat_id), str(question[1]))).fetchall()[0][0] manager = connection.cursor().execute( 'SELECT who_answer FROM messages WHERE id=?', (msg_id, )).fetchall() connection.close() if manager.__len__() != 1: connection = Db().connect() md_name = connection.cursor().execute( 'SELECT name FROM users WHERE chat_id=?', (manager[0][0], )).fetchall() connection.commit() print(manager.__len__(), manager) bot.send_message( chat_id=call.from_user.id, text=f'Модератор {md_name} уже отвечает на этот вопрос.') else: connection = Db().connect() connection.cursor().execute( 'UPDATE messages SET who_answer=? WHERE id=?', (str(call.from_user.id), str(msg_id))) connection.commit() connection.close() bot.send_message(chat_id=call.from_user.id, text='Теперь вы отвечаете на это сообщение') if call.data == 'history': connection = Db().connect() chat_id = str(call.message.text).split( 'Сообщение от пользователя')[1].split('\n')[0].split('(')[0] history = connection.cursor().execute( 'SELECT message, answer FROM messages WHERE chat_id=? AND status=?', (chat_id, 'Resolved')).fetchall() for pare in history: bot.send_message( chat_id=call.from_user.id, text=f'*Пользователь*:\n{pare[0]}\n*Модератор*:\n{pare[1]}', parse_mode='markdown')
def registerButton(self): """ sends the info to the database and checks if the fields are acceptable """ name = self.txtName.text() email = self.txtEmail.text() username = self.txtUsername.text() password = self.txtPassword.text() password2 = self.txtPassword2.text() if self.checkFields(username, name, email, password): self.showMessage("Error", "All fields must be filled") else: if (self.checkPassword(password, password2)): if (Db().registerCheck(username, email)): Db().insertTable(name, username, email, password) self.showMessage("Success", "Registration successful") self.clearField() self.trainModel() else: self.showMessage("Error", "Username or Email already existing") self.clearField() else: self.showMessage("Error", "Passwords doesn't match")
def process_successful_payment(message: telebot.types.Message): connection = Db().connect() connection.cursor().execute('UPDATE payments SET status=? WHERE chat_id=?', ('Paid', message.chat.id)) connection.commit() connection = Db().connect() connection.cursor().execute( 'UPDATE users SET subs_start=?, subs_end=? WHERE chat_id=?', (datetime.now().strftime('%d.%m.%y'), (datetime.now() + timedelta(31)).strftime('%d.%m.%y'), message.chat.id)) connection.commit() bot.send_message(chat_id=message.chat.id, text=msg['successful_payment'])
def registerButton(self): name = self.txtName.text() email = self.txtEmail.text() username = self.txtUsername.text() password = self.txtPassword.text() password2 = self.txtPassword2.text() if self.checkFields(username,name,email,password): self.showMessage("Error", "All fields must be filled") else: if(self.checkPassword(password,password2)): insertDb = Db() Db().insertTable(name,username,email,password) self.showMessage("Success","Registration successul") self.clearField() else: self.showMessage("Error","Passwords doesn't match")
def adminviewrating(): ob = Db() res = ob.select( "select avg(rating.rate)as rate1,doctor.* from rating, doctor where rating.did=doctor.did group by rating.did" ) return render_template("adminviewrating.html", a=res)
def confirm_session(): form = SessionConfirmationForm() if form.validate_on_submit(): name = form.name.data tuteeEmail = form.tuteeEmail.data tutorEmail = form.tutorEmail.data date = str(form.sessionDate.data) hours = form.hours.data comments = form.comments.data # Connect to database DB = Db() # Make sure tuteeEmail isn't the same as tutorEmail if tuteeEmail == tutorEmail: flash( "Your email can't be the same as your tutor's email. Please try again.", "error") return render_template("confirmSession.html", form=form) # Check if tutor exists tutor = DB.execute( "SELECT * from tutors WHERE email = %s AND status = 1", (tutorEmail, )) if not tutor: flash( Markup( f"The email you entered doesn't seem to be registered as a tutor. Please check to make sure you typed it correctly, \ or <a href={ url_for('contact') }>contact us</a> if you think this is an error." ), "error") return render_template("confirmSession.html", form=form) # Log tutee name and email if they don't exist in the database, then get their ID tutee = DB.execute("SELECT * from tutees where email = %s", (tuteeEmail, )) tuteeID = -1 if tutee: tuteeID = tutee[0]["tuteeID"] else: DB.execute( "INSERT INTO tutees (name, email, status) VALUES (%s, %s, %s)", (name, tuteeEmail, 0)) tuteeID = DB.execute("SELECT LAST_INSERT_ID() AS id")[0]["id"] # Log session in database DB.execute( "INSERT INTO sessionLogs (sessionDate, hours, comments, tutorID, tuteeID) VALUES (%s, %s, %s, %s, %s)", (date, hours, comments, tutor[0]["tutorID"], tuteeID)) # Give tutor the appropriate hours DB.execute("UPDATE tutors SET hours = hours + %s WHERE email = %s", (hours, tutorEmail)) flash( "Thank you for confirming! We've given your tutor their volunteer hours." ) return redirect(url_for("confirm_session")) return render_template("confirmSession.html", form=form)
def __init__(self, *args, **kwargs): discord.Client.__init__(self, *args, **kwargs) self.redis_url = kwargs.get('redis_url') self.db = Db(self.redis_url) self.plugin_manager = PluginManager(self) self.plugin_manager.load_all() self.last_messages = []
def init(db_path): if (not utils.is_database_exists(db_path)): print('Database was not found. Do you want to create a new one?') a = input('Yes/no: ') if (a == 'no'): sys.exit(1) else: db = Db(db_path) db.init() db.close()
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.redis_url = kwargs.get('redis_url') self.mongo_url = kwargs.get('mongo_url') self.dd_agent_url = kwargs.get('dd_agent_url') self.db = Db(self.redis_url, self.mongo_url, self.loop) self.plugin_manager = PluginManager(self) self.plugin_manager.load_all() self.last_messages = [] self.stats = DDAgent(self.dd_agent_url)
def process_pre_checkout_query( pre_checkout_query: telebot.types.PreCheckoutQuery): connection = Db().connect() connection.cursor().execute( 'INSERT INTO payments(chat_id, status, date) VALUES (?,?,?)', (pre_checkout_query.from_user.id, 'Not paid', datetime.now().strftime('%d.%m.%y'))) connection.commit() bot.answer_pre_checkout_query(pre_checkout_query.id, ok=True)
def registerButton(self): username = self.txtUsername.text() password = self.txtPassword.text() password2 = self.txtPassword2.text() if self.checkFields(username, password): self.showMessage("Error", "小主,所有信息都要填写哦|д・)っ") else: if (self.checkPassword(password, password2)): insertDb = Db() Db().insertTable(username, password) self.showMessage("Success", "注册成功啦!(⁄⁄•⁄ω⁄•⁄⁄)") self.clearField() # self.Dialog.setVisible(False) self.homWindow = QtWidgets.QDialog() self.ui = Ui_Dialog5() self.ui.setupUi(self.homWindow) self.homWindow.show() else: self.showMessage("Error", "前后密码不匹配哦⊙̆̈_⊙̆̈")
def save_name(message): connection = Db().connect() connection.cursor().execute( 'UPDATE users SET name=? WHERE chat_id=?', (message.text, message.chat.id)) connection.commit() connection.close() get_company = bot.send_message(chat_id=message.chat.id, text=msg['company']) bot.register_next_step_handler(get_company, save_company)
def mongo_db_test(): from database_mongo import Db import time db = Db() db.init() current_timestamp = time.time() * 1000 db.add_pending_messages("asdasdasd", 1, "{}", current_timestamp) db.add_pending_messages("asdasdasd", 2, "{}") time.time() * 1000 print db.fetch_inbox_messages("asdasdasd", -1, -1, current_timestamp - 100)
def loginCheck(self): username = self.txtUsername.text() password = self.txtPassword.text() getDb = Db() result = getDb.loginCheck(username, password) if (result): self.welcomePage() self.clearField() print(result) else: print("password wrong") self.showMessage("Warning", "Invalid Username and Password")
def saveContact(self): id = self.id first_name = self.first_name last_name = self.last_name telephone = self.telephone email = self.email url = self.url notes = self.notes db = Db() if (first_name != None and first_name != "" and last_name != None and last_name != ""): db.saveContact(id, first_name, last_name, telephone, email, url, notes)
def loginCheck(self): username = self.txtUsername.text() print(username) fh = open('database/username.txt', 'w+') fh.write(str(username)) fh.close() password = self.txtPassword.text() getDb = Db() result = getDb.loginCheck(username, password) if (result): self.welcomePage() self.clearField() print(result) else: print("密码错误哦,再输一次吧(≖ω≖✿)") self.showMessage("Warning", "诶,这是不合理的用户名和密码哦~(¯•ω•¯)")
def mongo_db_test_1(): # to test fetch node from database_mongo import Db import time db = Db() db.init(user_name="abhinav", password="******", host="104.199.129.250", namespace="samosa_messaging_v2") # print db.fetch_inbox_messages("df44c88cdaa36e4de1c5bf9c36968078", -1, -1, 1468524512476) # db.update_node_info("g3cK4ljIyh1468240301", num_connections=1650, num_max_connections=1500) print db.get_a_connection_node()
def test2(): from websocket._core import create_connection from bson import json_util import cookies from database import Db import config import time db = Db() db.init() # this is where user connects to nodes db.remove_client_nodes("abhinav") client_node_id1 = db.create_node("abhinav", None, None, None) # client client_node_id2 = db.create_node("abhinav", None, None, None) # client print "creating nodes", client_node_id1, client_node_id2 auth_key_client1 = cookies.create_signed_value( config.SERVER_SECRET, "auth", json_util.dumps({'node_id': client_node_id1})) auth_key_client2 = cookies.create_signed_value( config.SERVER_SECRET, "auth", json_util.dumps({'node_id': client_node_id2})) ws1 = create_connection("ws://192.168.1.146:8081/connect?auth_key=" + auth_key_client1) print "created_connection 1" ws2 = create_connection("ws://192.168.1.146:8083/connect?auth_key=" + auth_key_client2) print "created_connection 2" time.sleep(1) ws1.send( json_util.dumps({ 'dest_id': client_node_id2, "payload": "Hello world" })) time.sleep(0.1) print ws2.recv() time.sleep(0.1) print ws1.recv() ws1.send_close() ws2.send_close()
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.redis_url = kwargs.get('redis_url') self.mongo_url = kwargs.get('mongo_url') self.dd_agent_url = kwargs.get('dd_agent_url') self.sentry_dsn = kwargs.get('sentry_dsn') self.db = Db(self.redis_url, self.mongo_url, self.loop) self.plugin_manager = PluginManager(self) self.plugin_manager.load_all() self.last_messages = [] self.stats = DDAgent(self.dd_agent_url) self.voice_sessions_ids = dict() if self.shard_id is not None: self.shard = [self.shard_id, self.shard_count] else: self.shard = [0, 1]
def save_company(message): connection = Db().connect() connection.cursor().execute( 'UPDATE users SET company=? WHERE chat_id=?', (message.text, message.chat.id)) connection.commit() connection.close() markup1 = telebot.types.InlineKeyboardMarkup(row_width=1) btn1 = telebot.types.InlineKeyboardButton(text='Получить доступ', callback_data='invoice') btn2 = telebot.types.InlineKeyboardButton(text='Договор оферты', callback_data='dogovor', url='https://google.com') btn3 = telebot.types.InlineKeyboardButton(text='О компании', callback_data='about', url='https://google.com') markup1.add(btn1, btn2, btn3) bot.send_message(chat_id=message.chat.id, text=msg['start'], reply_markup=markup1)
def contact_handler(message): try: connection = Db().connect() connection.cursor().execute( 'INSERT INTO users(chat_id, username, phone, date) VALUES (?,?,?,?)', (message.chat.id, message.from_user.username, message.contact.phone_number, datetime.now().strftime('%d.%m.%y'))) connection.commit() connection.close() markup = telebot.types.ReplyKeyboardRemove() get_name = bot.send_message(chat_id=message.chat.id, text=msg['name'], reply_markup=markup) bot.register_next_step_handler(get_name, save_name) except: bot.send_message( chat_id=message.chat.id, text= 'Вы не можете зарегистрироваться без username. Для того, чтобы его указать, перейдите в настройки вашего Telegram и укажите username' ) pass
def hours(): form = HoursForm() if form.validate_on_submit(): email = form.email.data DB = Db() tutor = DB.execute( "SELECT tutorID, hours FROM tutors WHERE email = %s AND status = 1", (email, )) # Check if email is registered as a tutor if not tutor: flash( Markup( f"This email doesn't seem to be registered as a tutor. Please check to make sure you typed it correctly, \ or <a href={ url_for('contact') }>contact us</a> if you think this is an error." ), "error") return render_template("hours.html", form=form) # Convert hours to integer if hours is a whole number hours = tutor[0]['hours'] hours = hours if hours % 1 != 0 else int(hours) if hours == 1: flash( Markup( f"You currently have 1 volunteer hour. Please <a href={ url_for('contact') }>contact us</a> if you think this is an error." )) else: flash( Markup( f"You currently have { hours } volunteer hours. Please <a href={ url_for('contact') }>contact us</a> if you think this is an error." )) return redirect(url_for("hours")) return render_template("hours.html", form=form)
def check_password(self): """ checks the login info """ msg = QMessageBox() username = self.lineEdit_username.text() password = self.lineEdit_password.text() getDb = Db() result = getDb.loginCheck(username, password) if result: msg = QMessageBox() msg.setWindowIcon(QtGui.QIcon('eye-512.png')) msg.setWindowTitle("Login") msg.setText("Success") x = msg.exec_() # this will show our message box self.login() else: msg = QMessageBox() msg.setWindowIcon(QtGui.QIcon('eye-512.png')) msg.setWindowTitle("Login") msg.setText("Incorrect Password") x = msg.exec_() # this will show our message box
:param proc_db: :return diff: """ diff = [] i = 0 while True: if proc_file[i] != proc_db[i]: diff.append(proc_file[i]) diff.append(proc_db[i]) break else: i += 1 return diff if __name__ == '__main__': db = Db() pf = Procfile('testdata/stored_procs.sql') procname = 'dbo.uspGetBillOfMaterials' proc_file = pf.get_procedure(procname) proc_db = db.get_procedure(procname) actual = compare_two_list(proc_file, proc_db) if actual: print('Különbség van az adatbázisban és a fájlban a ' + procname + ' eljárásban:') print('Fájl') print(actual[0]) print('DB') print(actual[1])
def getContactFromId(self): db = Db() contact = db.getContactfromId(self.id) return contact
def getContactFromText(self, text): db = Db() contacts = db.getContactFromText(text) return contacts
def updateContact(self): db = Db() db.updateContact(self.first_name, self.last_name, self.telephone, self.email, self.url, self.notes, self.id)
def showContacts(self): db = Db() contacts = db.getContacts() return contacts
def getContactFromTagAndText(self, text): db = Db() result = db.getContactFromTagAndText(text, self.tag) return result
def deleteContactTagsFromId(self): db = Db() id = self.id db.deleteContactTagsFromId(id)