|
@@ -0,0 +1,166 @@
|
|
|
+#Библиотеки
|
|
|
+from multiprocessing import connection
|
|
|
+import xmpp
|
|
|
+import pymysql
|
|
|
+from config import host, user, password, db_name, jid, jidpassword
|
|
|
+from BotClass import JabberBot
|
|
|
+#Проверка соединения и само соединение
|
|
|
+try:
|
|
|
+ connection = pymysql.connect(
|
|
|
+ host=host,
|
|
|
+ port=3306,
|
|
|
+ user=user,
|
|
|
+ password=password,
|
|
|
+ database=db_name,
|
|
|
+ cursorclass=pymysql.cursors.DictCursor
|
|
|
+ )
|
|
|
+ class OrderS:
|
|
|
+ Name = ""
|
|
|
+ Description = ""
|
|
|
+ Price = float(0)
|
|
|
+ idUser = int(0)
|
|
|
+ User = ""
|
|
|
+ def __init__(self, User, Name, IdUser):
|
|
|
+ self.Name = Name
|
|
|
+ self.Description = ""
|
|
|
+ self.Price = float(0)
|
|
|
+ self.idUser = IdUser
|
|
|
+ self.User = User
|
|
|
+ def display_info(self):
|
|
|
+ print(self.Name + self.Description + self.Price + self.User + self.idUser)
|
|
|
+ print("Successfully connection...")
|
|
|
+except Exception as ex:
|
|
|
+ print("Error connection to database...")
|
|
|
+ print(ex)
|
|
|
+#Конфиг для авторизации бота
|
|
|
+#config = {
|
|
|
+# 'jid': '',
|
|
|
+# 'pass': ''
|
|
|
+#}
|
|
|
+#Добавление пользователя в базу данных
|
|
|
+def add_user(userName):
|
|
|
+ with connection.cursor() as cursor:
|
|
|
+ select_all_rows = "SELECT * FROM `user`"
|
|
|
+ cursor.execute(select_all_rows)
|
|
|
+ rows = cursor.fetchall()
|
|
|
+ i = 0
|
|
|
+ stringUser = str(userName).split("/")[0]
|
|
|
+ for row in rows:
|
|
|
+ if str(row['FullName']).split("/")[0] == stringUser:
|
|
|
+ i += 1
|
|
|
+ if i == 0:
|
|
|
+ insert_user = "INSERT INTO testbotdb.user (FullName, IdStatus) VALUES(%s, %s)"
|
|
|
+ val = (stringUser, 1)
|
|
|
+ cursor.execute(insert_user, val)
|
|
|
+ connection.commit()
|
|
|
+ return True
|
|
|
+ else:
|
|
|
+ i = 0
|
|
|
+ return False
|
|
|
+
|
|
|
+IDORDER = 0
|
|
|
+mylist = set()
|
|
|
+#Основной метод для обработки сообщинй от пользователя
|
|
|
+def message_handler(conn, mess):
|
|
|
+
|
|
|
+ text = mess.getBody()
|
|
|
+ user = mess.getFrom()
|
|
|
+ #Проверка статуса пользователя
|
|
|
+ with connection.cursor() as cursor:
|
|
|
+ sqlproverka = "SELECT * FROM testbotdb.user WHERE Fullname = %s"
|
|
|
+ cursor.execute(sqlproverka, user)
|
|
|
+ status = cursor.fetchone()
|
|
|
+
|
|
|
+ if add_user(user):
|
|
|
+ conn.send(xmpp.Message(user, 'Вас приветствует тестовый бот для создания, просмотра и управления заказами.\nВоспользуйтесь коммандой help для ознокомления с моим функционалом.'))
|
|
|
+
|
|
|
+ elif status['IdStatus'] == 2 and status['FullName'] == user and text != 'cancel':
|
|
|
+ InsertOderName(text, status['idUser'], user)
|
|
|
+ conn.send(xmpp.Message(user, 'Укажите описание заказа:'))
|
|
|
+
|
|
|
+ elif status['IdStatus'] == 3 and status['FullName'] == user and text != 'cancel':
|
|
|
+ InsertOderDescription(text, IDORDER, user)
|
|
|
+ print(IDORDER)
|
|
|
+ conn.send(xmpp.Message(user, 'Укажите цену:'))
|
|
|
+
|
|
|
+ elif status['IdStatus'] == 4 and status['FullName'] == user and text != 'cancel':
|
|
|
+ InsertOderPrice(text, IDORDER, user)
|
|
|
+ print(IDORDER)
|
|
|
+ conn.send(xmpp.Message(user, 'Вы точно хотите добавить заказ[y/n]:'))
|
|
|
+
|
|
|
+ elif status['IdStatus'] == 5 and status['FullName'] == user and text != 'cancel':
|
|
|
+ if text == 'y':
|
|
|
+ conn.send(xmpp.Message(user, 'Заказ успешно добавлен!'))
|
|
|
+ else:
|
|
|
+ changeOrderStatus(1, user)
|
|
|
+ conn.send(xmpp.Message(user, 'Отменено.'))
|
|
|
+
|
|
|
+ else:
|
|
|
+ if text == "help":
|
|
|
+ conn.send(xmpp.Message(user, '\nhelp - предоставляет список доступных комманд\ncancel - отмена любой из операций\naddorder - добавить заказ\ndeleteorder - удалить заказ\nlistorder - показывает список заказов\nwheather - показывает погоду'))
|
|
|
+ elif text == "cancel":
|
|
|
+ changeOrderStatus(1, user)
|
|
|
+ conn.send(xmpp.Message(user, 'Отменено.'))
|
|
|
+ elif text == "addorder":
|
|
|
+ changeOrderStatus(2, user)
|
|
|
+ conn.send(xmpp.Message(user, 'Укажите имя заказа:'))
|
|
|
+ else:
|
|
|
+ conn.send(xmpp.Message(user, 'Комманда не определена. Воспользуйтесь командой help.'))
|
|
|
+#Изменения статуса
|
|
|
+def changeOrderStatus(statusId, user):
|
|
|
+ with connection.cursor() as cursor:
|
|
|
+ sql = "UPDATE testbotdb.user SET IdStatus = %s WHERE FullName = %s"
|
|
|
+ val = (statusId, user)
|
|
|
+ cursor.execute(sql, val)
|
|
|
+ connection.commit()
|
|
|
+#Метод для добавления имени и пользователя
|
|
|
+def InsertOderName(ordername, orderiduser, user):
|
|
|
+ try:
|
|
|
+ with connection.cursor() as cursor:
|
|
|
+ sqlidUser = "SELECT idUser FROM testbotdb.user WHERE Fullname = %s"
|
|
|
+ cursor.execute(sqlidUser, user)
|
|
|
+ idUser = cursor.fetchone()
|
|
|
+ print(idUser['idUser'])
|
|
|
+ sql = "INSERT INTO testbotdb.order (NameOrder, IdUser) VALUES (%s, %s)"
|
|
|
+ val = (ordername, idUser['idUser'])
|
|
|
+ #orderss.append(OrderS(user, ordername, idUser['idUser']))
|
|
|
+ order = OrderS(user, ordername, idUser['idUser'])
|
|
|
+ orders = [order]
|
|
|
+ resultorder = sorted(orders, key=lambda ord: ord.User)
|
|
|
+ mylist.add(OrderS(user, ordername, idUser['idUser']))
|
|
|
+ for item in resultorder:
|
|
|
+ if user == item.User:
|
|
|
+ print(item.Name)
|
|
|
+ #cursor.execute(sql, val)
|
|
|
+ #connection.commit()
|
|
|
+ #global IDORDER
|
|
|
+ #IDORDER = cursor.lastrowid
|
|
|
+ #changeOrderStatus(3, user)
|
|
|
+ except Exception as ex:
|
|
|
+ print(ex)
|
|
|
+#Метод для добавления описания
|
|
|
+def InsertOderDescription(orderdescription, idOrder, user):
|
|
|
+ try:
|
|
|
+ with connection.cursor() as cursor:
|
|
|
+ sql = "UPDATE testbotdb.order SET Description = %s WHERE idOrder = %s"
|
|
|
+ val = (orderdescription, idOrder)
|
|
|
+ cursor.execute(sql, val)
|
|
|
+ connection.commit()
|
|
|
+ changeOrderStatus(4, user)
|
|
|
+ except Exception as ex:
|
|
|
+ print(ex)
|
|
|
+#Метод для добавления цены
|
|
|
+def InsertOderPrice(orderprice, idOrder, user):
|
|
|
+ try:
|
|
|
+ with connection.cursor() as cursor:
|
|
|
+ sql = "UPDATE testbotdb.order SET Price = %s WHERE idOrder = %s"
|
|
|
+ val = (float(orderprice), idOrder)
|
|
|
+ cursor.execute(sql, val)
|
|
|
+ connection.commit()
|
|
|
+ changeOrderStatus(5, user)
|
|
|
+ except Exception as ex:
|
|
|
+ print(ex)
|
|
|
+#Авторизация и запуск бота
|
|
|
+bot = JabberBot(jid, jidpassword)
|
|
|
+bot.register_handler('message', message_handler)
|
|
|
+bot.start()
|