def __ProcessFee(self, msg: str): if msg == ld.CancelKey or msg == "/start": log.info( self.username + " has been cancelled {0} process".format(self.__reqType.name)) self.__deleteProcessMessage() self.Start() return try: self.__fee = float(msg) self.currentStep = RequestSteps.EnterBank keyboard = InlineKeyboardMarkup(row_width=1) keyboard.row( InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.CancelKey), callback_data=ld.CancelKey)) reply = self.__bot.send_message(self.__chatId, ld.get_translate( self.__db, self.username, ld.EnterBankNameKey), reply_markup=keyboard) self.__processMsgId = reply.message_id except Exception: self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.WrongInputKey))
def __ProcessEnterCurrency(self, msg: str): if msg == ld.CancelKey or msg == "/start": log.info( self.username + " has been cancelled {0} process".format(self.__reqType.name)) self.__deleteProcessMessage() self.Start() return assets = self.__db.GetAssetsList() if msg not in assets: self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.WrongInputKey)) return self.__currency = msg self.currentStep = RequestSteps.EnterQuantity self.__deleteProcessMessage() keyboard = InlineKeyboardMarkup(row_width=1) keyboard.row( InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.CancelKey), callback_data=ld.CancelKey)) reply = self.__bot.send_message(self.__chatId, ld.get_translate( self.__db, self.username, ld.EnterQuantityMsgKey), reply_markup=keyboard) self.__processMsgId = reply.message_id
def __ProcessChangeCurrency(self, msg: str): if msg == ld.CancelKey or msg == "/start": print(self.username + " has been cancelled changing request process") self.__deleteProcessMessage() self.Start() return if not (msg == ld.SkipKey): assets = self.__db.GetAssetsList() if msg not in assets: self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.WrongInputKey)) return self.__currency = msg self.__deleteProcessMessage() self.currentStep = RequestSteps.ChangeQuantity keyboard = InlineKeyboardMarkup(row_width=1) keyboard.row( InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.CancelKey), callback_data=ld.CancelKey), InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.SkipKey), callback_data=ld.SkipKey)) reply = self.__bot.send_message(self.__chatId, ld.get_translate( self.__db, self.username, ld.EnterQuantityMsgKey), reply_markup=keyboard) self.__processMsgId = reply.message_id
def __ProcessFeeType(self, msg: str): if msg == ld.CancelKey or msg == "/start": log.info(self.username + " cancelled {0} process".format(self.__reqType.name)) self.__deleteProcessMessage() self.Start() return self.__feeType = FeeTypes.Nobody if msg == ld.SellerKey: self.__feeType = FeeTypes.Seller elif msg == ld.BuyerKey: self.__feeType = FeeTypes.Buyer keyboard = InlineKeyboardMarkup(row_width=1) keyboard.row( InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.CancelKey), callback_data=ld.CancelKey)) if self.__feeType == FeeTypes.Nobody: self.__fee = 0.0 self.currentStep = RequestSteps.EnterBank reply = self.__bot.send_message(self.__chatId, ld.get_translate( self.__db, self.username, ld.EnterBankNameKey), reply_markup=keyboard) self.__processMsgId = reply.message_id else: self.currentStep = RequestSteps.EnterFee reply = self.__bot.send_message(self.__chatId, ld.get_translate( self.__db, self.username, ld.EnterFeeMsgKey), reply_markup=keyboard) self.__processMsgId = reply.message_id
def __ProcessChangeBank(self, msg: str): if msg == ld.CancelKey or msg == "/start": print(self.username + " has been cancelled changing request process") self.__deleteProcessMessage() self.Start() return if not (msg == ld.SkipKey): self.__bank = self.__StripTagsRegex(msg) self.currentStep = RequestSteps.ChangeEndDate keyboard = InlineKeyboardMarkup(row_width=1) keyboard.row( InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.CancelKey), callback_data=ld.CancelKey), InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.SkipKey), callback_data=ld.SkipKey)) reply = self.__bot.send_message(self.__chatId, ld.get_translate( self.__db, self.username, ld.EnterReqDurationKey), reply_markup=keyboard) self.__processMsgId = reply.message_id
def __getResultsForSql(self, sql, callUser): self.cur.execute(sql) result = self.cur.fetchall() results = [] for r in result: number = r[0] username = r[1] reqType = self.__getLocalizedRequestType(RequestType(r[2]), callUser) quantity = r[3] currency = r[4] fee = str(r[6]).replace(",", ".") bank = r[5] startDate = r[7] endDate = r[8] whoPayFee = "" if float(fee) > 0: whoPayFee = ld.get_translate(self, callUser, ld.FeePayBuyerKey) elif float(fee) < 0: whoPayFee = ld.get_translate(self, callUser, ld.FeePaySellerKey) req = ld.get_translate(self, callUser, ld.RequestResultStringTemplate).format( number, username, reqType, quantity, currency, fee, whoPayFee, bank, startDate, endDate) results.append(req) return results
def __ProcessEndDate(self, msg: str): if msg == ld.CancelKey or msg == "/start": print( self.username + " has been cancelled {0} process".format(self.__reqType.name)) self.__deleteProcessMessage() self.Start() return try: self.__daysQuantity = int(msg) now = datetime.now() delta = timedelta(days=self.__daysQuantity, hours=0, minutes=0) if self.__feeType == FeeTypes.Seller and self.__fee > 0.0: self.__fee = -self.__fee reqId = self.__db.AddRequest(self.username, self.__reqType, self.__quantity, self.__currency, self.__bank, self.__fee, now, now + delta) self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.SuccessfulRequestKey)) self.Start() reqStr = self.__db.GetRequest(reqId, self.username) self.__SendNotifications( ld.get_translate(self.__db, self.username, ld.NewReqNotifKey).format(reqStr)) except Exception as ex: print(ex) self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.WrongInputKey))
def __ProcessShowMy(self): myReqs = self.__db.GetRequestsFor(self.username, self.username) if len(myReqs) == 0: self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.EmptyKey)) return for req in myReqs: idx1 = req.find('(') idx2 = req.find(')') if idx1 < 0 or idx2 < 0: continue reqId = req[idx1:idx2 + 1] keyboard = InlineKeyboardMarkup(row_width=1) keyboard.row( InlineKeyboardButton("{0} {1}".format( ld.get_translate(self.__db, self.username, ld.RemoveKey), reqId), callback_data="{0} {1}".format( ld.RemoveKey, reqId)), InlineKeyboardButton("{0} {1}".format( ld.get_translate(self.__db, self.username, ld.ChangeKey), reqId), callback_data="{0} {1}".format( ld.ChangeKey, reqId))) self.__bot.send_message(self.__chatId, req, parse_mode="HTML", reply_markup=keyboard)
def __ProcessVote(self, msg: str): if msg == ld.CancelKey or msg == "/start": print(self.username + " has been cancelled {0} process".format( self.currentStep.name)) self.Start() return votedUser = msg.strip('"').lstrip('@') if not self.__db.IsUserRegistered(votedUser): self.__bot.send_message( self.__chatId, ld.get_translate( self.__db, self.username, ld.VotedUserNotRegisteredKey).format(votedUser)) return if self.__db.IsAlreadyVotedByUser(self.username, votedUser): self.__bot.send_message( self.__chatId, ld.get_translate( self.__db, self.username, ld.VotedUserAlreadyVotedKey).format(votedUser)) return if self.username == votedUser: self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.VotedUserIsMySelfKey)) return self.__db.Vote(self.username, votedUser) voteCount = self.__db.GetVotesCount(self.username) self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.VoteSuccessfulKey).format( votedUser, db.DB.MaxVotes - voteCount)) self.Start()
def __ProcessChangeFee(self, msg: str): if msg == ld.CancelKey or msg == "/start": print(self.username + " has been cancelled changing request process") self.__deleteProcessMessage() self.Start() return if not (msg == ld.SkipKey): try: self.__fee = float(msg) except: self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.WrongInputKey)) return self.__deleteProcessMessage() self.currentStep = RequestSteps.ChangeBank keyboard = InlineKeyboardMarkup(row_width=1) keyboard.row( InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.CancelKey), callback_data=ld.CancelKey), InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.SkipKey), callback_data=ld.SkipKey)) reply = self.__bot.send_message(self.__chatId, ld.get_translate( self.__db, self.username, ld.EnterBankNameKey), reply_markup=keyboard) self.__processMsgId = reply.message_id
def __ProcessShowAll(self, pageNumber: int): limit = 5 offset = limit * (pageNumber - 1) allReqs = self.__db.GetAllRequests(self.username, offset, limit) if len(allReqs) == 0: self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.EmptyKey)) return for req in allReqs: keyboard = InlineKeyboardMarkup(row_width=1) buttonTextKey = ld.AcceptSellRequestKey if db.RequestType( req[2]) == db.RequestType.Sell else ld.AcceptBuyRequestKey keyboard.row( InlineKeyboardButton(ld.get_translate(self.__db, self.username, buttonTextKey), callback_data="{0}{1}".format( buttonTextKey, req[0]))) formattedReq = self.__getFormattedRequest(req) if str(req[1]) == self.username: keyboard = None reply = self.__bot.send_message(self.__chatId, formattedReq, parse_mode="HTML", reply_markup=keyboard) self.__allReqMsgIds.append(reply.message_id) reqCount = self.__db.GetAllRequestsCount() showPrevButton = pageNumber > 1 showNextButton = (reqCount - (limit + limit * (pageNumber - 1))) > 0 keyboard = None if showNextButton or showPrevButton: keyboard = ReplyKeyboardMarkup(row_width=2, resize_keyboard=True, one_time_keyboard=True) buttons = [] if showPrevButton: buttons.append(KeyboardButton("⬅️")) if showNextButton: buttons.append(KeyboardButton("➡️")) keyboard.add(*buttons) self.__isKeyboardActive = True maxPageNumber = reqCount // limit if reqCount % limit > 0: maxPageNumber += 1 reply = self.__bot.send_message(self.__chatId, "Page {0} of {1}".format( pageNumber, maxPageNumber), parse_mode="HTML", reply_markup=keyboard) self.__allReqMsgIds.append(reply.message_id)
def handle_private_message(message: Message): if message.from_user.username == None or len(message.from_user.username) == 0: bot.send_message(message.chat.id, """Вам сначала нужно установить никнейм в телеграме. You need to set your username in Telegram first.""") return if not db.IsUserRegistered(message.from_user.username): bot.send_message(message.chat.id, ld.get_translate(db, message.from_user.username, ld.PleaseRegisterGroupChatKey)) return username = message.from_user.username db.SetUserChatId(username, message.chat.id) if (message.text.startswith("/start")): if not (username in userProcesses): userProcesses[username] = UserRequestProcess(bot, db, username, message.chat.id) req = userProcesses[username] if req.currentStep == RequestSteps.Start: req.Start() else: req.ProcessMessage("/start") elif (username in userProcesses) and ((userProcesses[username].currentStep != RequestSteps.Start) or message.text == "⬅️" or message.text == "➡️"): userProcesses[username].ProcessMessage(message.text) else: usage = """<b>Использование:</b> /start - Начало процесса <b>Usage:</b> /start - start process""" bot.send_message(message.chat.id, usage, parse_mode="HTML")
def __GetMarkupForUnvote(self, usernameList: list): keyboard = InlineKeyboardMarkup(row_width=len(usernameList) + 1) for username in usernameList: keyboard.row(InlineKeyboardButton(username, callback_data=username)) keyboard.row( InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.CancelKey), callback_data=ld.CancelKey)) return keyboard
def __ProcessChangeEndDate(self, msg: str): if msg == ld.CancelKey or msg == "/start": log.info(self.username + " has been cancelled changing request process") self.__deleteProcessMessage() self.Start() return if not (msg == ld.SkipKey): try: self.__daysQuantity = int(msg) except Exception: self.__daysQuantity = -1 self.__deleteProcessMessage() if self.__daysQuantity > 0: now = datetime.now() self.__startDate = now self.__endDate = now + timedelta(days=self.__daysQuantity) if self.__feeType >= 0: if (self.__feeType == FeeTypes.Seller and self.__fee > 0.0) or (self.__feeType == FeeTypes.Buyer and self.__fee < 0.0): self.__fee = -self.__fee elif self.__feeType == FeeTypes.Nobody: self.__fee = 0.0 self.__db.UpdateRequest( self.__reqIdForUpdate, self.username, self.__quantity, self.__currency, self.__bank, self.__fee, self.__startDate, self.__endDate, ) self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.SuccessfulChangeKey)) self.Start() reqStr = self.__db.GetRequest(self.__reqIdForUpdate, self.username) self.__SendNotifications( ld.get_translate(self.__db, self.username, ld.ChangedReqNotifKey).format(reqStr))
def __ProcessChangeFeeType(self, msg: str): if msg == ld.CancelKey or msg == "/start": log.info(self.username + " has been cancelled changing request process") self.__deleteProcessMessage() self.Start() return if not (msg == ld.SkipKey): self.__feeType = FeeTypes.Nobody if msg == ld.SellerKey: self.__feeType = FeeTypes.Seller elif msg == ld.BuyerKey: self.__feeType = FeeTypes.Buyer self.__deleteProcessMessage() keyboard = InlineKeyboardMarkup(row_width=1) msg = ld.get_translate(self.__db, self.username, ld.EnterFeeMsgKey) if self.__feeType == FeeTypes.Nobody or self.__feeType == -1: if self.__feeType == FeeTypes.Nobody: self.__fee = 0.0 self.currentStep = RequestSteps.ChangeBank msg = ld.get_translate(self.__db, self.username, ld.EnterBankNameKey) else: self.currentStep = RequestSteps.ChangeFee keyboard.row( InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.CancelKey), callback_data=ld.CancelKey), InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.SkipKey), callback_data=ld.SkipKey), ) reply = self.__bot.send_message(self.__chatId, msg, reply_markup=keyboard) self.__processMsgId = reply.message_id
def __ProcessBank(self, msg: str): if msg == ld.CancelKey or msg == "/start": log.info(self.username + " cancelled {0} process".format(self.__reqType.name)) self.__deleteProcessMessage() self.Start() return self.__bank = self.__StripTagsRegex(msg) if len(self.__bank) == 0: self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.WrongInputKey)) return self.currentStep = RequestSteps.EnterEndDate keyboard = InlineKeyboardMarkup(row_width=1) keyboard.row( InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.CancelKey), callback_data=ld.CancelKey)) self.__bot.send_message(self.__chatId, ld.get_translate(self.__db, self.username, ld.EnterReqDurationKey), reply_markup=keyboard)
def __getFormattedRequest(self, req: tuple): number = req[0] username = req[1] reqType = self.__getLocalizedRequestType(db.RequestType(req[2]), self.username) quantity = req[3] currency = req[4] fee = str(req[6]).replace(",", ".") bank = req[5] startDate = req[7] endDate = req[8] whoPayFee = "" if float(fee) > 0: whoPayFee = ld.get_translate(self.__db, self.username, ld.FeePayBuyerKey) elif float(fee) < 0: whoPayFee = ld.get_translate(self.__db, self.username, ld.FeePaySellerKey) req = ld.get_translate(self.__db, self.username, ld.RequestResultStringTemplate).format( number, username, reqType, quantity, currency, fee, whoPayFee, bank, startDate, endDate) return req
def __GetMarkupForAssetList(self, assetsList: list, withSkipBtn: bool = False): assetsCount = len(assetsList) rowsCount = assetsCount // 5 if assetsCount % 5 > 0: rowsCount += 1 keyboard = InlineKeyboardMarkup(row_width=rowsCount + 1) buttons = [ InlineKeyboardButton(a, callback_data=a) for a in assetsList ] keyboard.add(*buttons) secondaryButtons = [ InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.CancelKey), callback_data=ld.CancelKey) ] if withSkipBtn: secondaryButtons.append( InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.SkipKey), callback_data=ld.SkipKey)) keyboard.row(*secondaryButtons) return keyboard
def __ProcessChangeQuantity(self, msg: str): if msg == ld.CancelKey or msg == "/start": log.info(self.username + " has been cancelled changing request process") self.__deleteProcessMessage() self.Start() return if not (msg == ld.SkipKey): try: parsedValue = self.__GetNumberFromString(msg) if not parsedValue: raise Exception("Parsing error!") self.__quantity = parsedValue except Exception: self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.WrongInputKey)) return self.__deleteProcessMessage() self.currentStep = RequestSteps.ChangeFeeType keyboard = InlineKeyboardMarkup(row_width=2) keyboard.row( InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.SellerKey), callback_data=ld.SellerKey), InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.BuyerKey), callback_data=ld.BuyerKey), ) keyboard.row( InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.NobodyKey), callback_data=ld.NobodyKey)) keyboard.row( InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.CancelKey), callback_data=ld.CancelKey), InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.SkipKey), callback_data=ld.SkipKey), ) reply = self.__bot.send_message(self.__chatId, ld.get_translate( self.__db, self.username, ld.SelectWhoPayFee), reply_markup=keyboard) self.__processMsgId = reply.message_id
def __ProcessUnvote(self, msg: str): if msg == ld.CancelKey or msg == "/start": print(self.username + " has been cancelled {0} process".format( self.currentStep.name)) self.__bot.delete_message(self.__chatId, self.__unvoteMsgId) self.Start() return votedUser = msg.lstrip('@') self.__db.Unvote(self.username, votedUser) voteCount = self.__db.GetVotesCount(self.username) self.__bot.delete_message(self.__chatId, self.__unvoteMsgId) self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.UnvoteSuccessfulKey).format( votedUser, db.DB.MaxVotes - voteCount)) self.Start()
def handle_group_message(message: Message): masterChatId = db.GetMasterChatId() if masterChatId != 0: masterChatAdmins = bot.get_chat_administrators(masterChatId) else: masterChatAdmins = [] if message.text.startswith("/setmasterchat"): if masterChatId != 0 and (masterChatId != message.chat.id): return if not message.from_user.username or len(message.from_user.username) == 0: bot.send_message(message.chat.id, """Установите сначала никнейм в телеграме Set 'username' first please""") return if (masterChatId == 0): masterChatId = message.chat.id masterChatAdmins = bot.get_chat_administrators(masterChatId) administrators = [user.user.username for user in masterChatAdmins] if not message.from_user.username in administrators: masterChatId = 0 masterChatAdmins = [] return print(message.from_user.username + " has been set masterchat") db.SetMasterChatId(masterChatId) bot.send_message(masterChatId, "Done") elif message.text.startswith("/list"): if masterChatId == 0 or len(masterChatAdmins) == 0: return if not message.from_user.username or len(message.from_user.username) == 0: bot.send_message(message.chat.id, """Установите сначала никнейм в телеграме Set 'username' first please""") return administrators = [user.user.username for user in masterChatAdmins] if not message.from_user.username in administrators: return reqList = db.GetAllFormattedRequests(message.from_user.username, 0, 50) if len(reqList) == 0: bot.send_message(message.chat.id, ld.get_translate(db, message.from_user.username, ld.EmptyKey)) else: idx = 0 reqCount = len(reqList) while idx < reqCount: count = min(10, reqCount - idx) lst = reqList[idx : idx + count] msg = "\n\n".join(lst) bot.send_message(message.chat.id, msg, parse_mode="HTML") idx += 10 elif message.text.startswith("/register"): if (masterChatId == 0): return if not message.from_user.username or len(message.from_user.username) == 0: bot.send_message(message.chat.id, """Установите сначала никнейм в телеграме Set 'username' first please""") return if (db.IsUserRegistered(message.from_user.username)): bot.send_message(message.chat.id, ld.get_translate(db, message.from_user.username, ld.UsernameAlreadyRegisteredKey).format(message.from_user.username)) return db.AddUser(message.from_user.username) bot.send_message(message.chat.id, """{0} зарегистрирован {0} has been registered""".format(message.from_user.username)) elif message.text.startswith("/unregister"): if (masterChatId == 0 or len(masterChatAdmins) == 0): return if not message.from_user.username or len(message.from_user.username) == 0: bot.send_message(message.chat.id, """Установите сначала никнейм в телеграме Set 'username' first please""") return administrators = [user.user.username for user in masterChatAdmins] if not message.from_user.username in administrators: return username = message.text.replace("/unregister", "").strip(' ').strip('@') if len(username) == 0: bot.send_message(message.chat.id, """Введите пожалуйста команду в виде <b>/unregister 'username'</b> Please, enter command as <b>/unregister 'username'</b>""", parse_mode="HTML") return if not db.IsUserRegistered(username): bot.send_message(message.chat.id, "User {0} is not registered".format(username)) return db.DeleteUser(username) bot.send_message(message.chat.id, "User {0} was deleted".format(username)) elif message.text.startswith("/escrowlist"): escrowList = db.GetEscrowList() if len(escrowList) == 0: bot.send_message(message.chat.id, ld.get_translate(db, message.from_user.username, ld.EmptyKey)) return result = "\n".join(escrowList) bot.send_message(message.chat.id, result, parse_mode="HTML") elif message.text.startswith("/stats"): if (masterChatId == 0 or len(masterChatAdmins) == 0): return if not message.from_user.username or len(message.from_user.username) == 0: bot.send_message(message.chat.id, """Установите сначала никнейм в телеграме Set 'username' first please""") return administrators = [user.user.username for user in masterChatAdmins] if not message.from_user.username in administrators: return usersCount = db.GetUsersCount() usersWithNotif = db.GetUsersCountWithNotifications() result = "\nusers: {0}\nwith notifications: {1}".format(usersCount, usersWithNotif) bot.send_message(message.chat.id, result) '''else:
def __AutoDeleteProcessingRequest(self, reqId): self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.AcceptRequestHasBeenAutoCancelledKey)) self.__DeleteProcessingRequest(reqId)
def __ProcessStartState(self, msg: str): self.__deleteAllReqMessages() if msg == ld.SellKey: print(self.username + " Sell") self.__deleteAllReqKeyboard() self.__reqType = db.RequestType.Sell self.currentStep = RequestSteps.EnterCurrency self.__deleteStartMessage() assets = self.__db.GetAssetsList() keyboard = self.__GetMarkupForAssetList(assets) reply = self.__bot.send_message(self.__chatId, ld.get_translate( self.__db, self.username, ld.SellingMsgKey), parse_mode="HTML", reply_markup=keyboard) self.__processMsgId = reply.message_id elif msg == ld.BuyKey: print(self.username + " Buy") self.__deleteAllReqKeyboard() self.__reqType = db.RequestType.Buy self.currentStep = RequestSteps.EnterCurrency self.__deleteStartMessage() assets = self.__db.GetAssetsList() keyboard = self.__GetMarkupForAssetList(assets) reply = self.__bot.send_message(self.__chatId, ld.get_translate( self.__db, self.username, ld.BuyingMsgKey), parse_mode="HTML", reply_markup=keyboard) self.__processMsgId = reply.message_id elif ld.RemoveKey in msg: parseResult = self.__ParseReqId(msg) if not parseResult[0]: self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.RemoveErrorKey)) return else: print(self.username + " are removing request #" + str(parseResult[1])) self.__db.DeleteReqWithId(parseResult[1]) self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.RemoveSuccessKey).format( parseResult[1])) elif ld.ChangeKey in msg: parseResult = self.__ParseReqId(msg) if not parseResult[0]: self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.ChangeErrorKey)) return else: print(self.username + " are changing request #" + str(parseResult[1])) self.currentStep = RequestSteps.ChangeCurrency self.__reqIdForUpdate = parseResult[1] req = self.__db.GetRawRequest(parseResult[1]) self.__reqType = db.RequestType(req[2]) self.__quantity = str(req[3]) self.__currency = req[4] self.__fee = float(req[6]) self.__bank = req[5] self.__startDate = datetime.strptime(req[7], "%d.%m.%Y") self.__endDate = datetime.strptime(req[8], "%d.%m.%Y") self.__daysQuantity = (self.__endDate - self.__startDate).days self.__deleteStartMessage() assets = self.__db.GetAssetsList() keyboard = self.__GetMarkupForAssetList(assets, True) reply = self.__bot.send_message(self.__chatId, ld.get_translate( self.__db, self.username, ld.ChangingMsgKey), parse_mode="HTML", reply_markup=keyboard) self.__processMsgId = reply.message_id elif msg == ld.ShowMyReqKey: print(self.username + " are browsing his requests") self.__deleteAllReqKeyboard() self.__ProcessShowMy() elif msg == ld.ShowAllReqKey: print(self.username + " are browsing all requests") self.__currentPage = 1 self.__ProcessShowAll(self.__currentPage) elif msg == "➡️": self.__currentPage += 1 self.__ProcessShowAll(self.__currentPage) elif msg == "⬅️": self.__currentPage -= 1 if (self.__currentPage < 1): self.__currentPage = 1 self.__ProcessShowAll(self.__currentPage) elif msg == ld.VoteKey: self.__deleteAllReqKeyboard() if (db.DB.MaxVotes - self.__db.GetVotesCount(self.username)) <= 0: self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.ZeroVotesKey)) return self.currentStep = RequestSteps.VoteUser keyboard = InlineKeyboardMarkup(row_width=1) keyboard.row( InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.CancelKey), callback_data=ld.CancelKey)) self.__bot.send_message(self.__chatId, ld.get_translate(self.__db, self.username, ld.VotingMsgKey), parse_mode="HTML", reply_markup=keyboard) elif msg == ld.UnvoteKey: self.__deleteAllReqKeyboard() votedUsersList = self.__db.GetMyVotedUsers(self.username) if len(votedUsersList) == 0: self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.VoteListEmptyKey)) return self.currentStep = RequestSteps.UnvoteUser reply = self.__bot.send_message( self.__chatId, "<b>{0}</b>".format( ld.get_translate(self.__db, self.username, ld.UnvoteKey)), parse_mode="HTML", reply_markup=self.__GetMarkupForUnvote(votedUsersList)) self.__unvoteMsgId = reply.message_id elif msg == ld.EscrowListKey: self.__deleteAllReqKeyboard() escrowList = self.__db.GetEscrowList() if len(escrowList) == 0: self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.EmptyKey)) return result = "\n".join(escrowList) self.__bot.send_message(self.__chatId, result, parse_mode="HTML") elif msg == ld.DisableNotifKey: self.__deleteAllReqKeyboard() print(self.username + " has been disabled notifications") self.__db.DeleteUserFromNotifications(self.username) self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.NotificationsDisabledKey)) self.Start() elif msg == ld.EnableNotifKey: self.__deleteAllReqKeyboard() print(self.username + " has been enabled notifications") if not self.__db.IsNotificationsRowExistForUser(self.username): self.__db.AddUserForNotifications(self.username, self.__chatId) self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.NotificationsEnabledKey)) self.Start() elif msg == ld.EnglishKey: self.__deleteAllReqKeyboard() self.__db.SetUserLanguage(self.username, ld.Languages.English) self.Start() elif msg == ld.RussianKey: self.__deleteAllReqKeyboard() self.__db.SetUserLanguage(self.username, ld.Languages.Russian) self.Start() elif msg.startswith(ld.AcceptBuyRequestKey) or msg.startswith( ld.AcceptSellRequestKey): try: msg = msg.replace(ld.AcceptBuyRequestKey, "") reqNum = int(msg.replace(ld.AcceptSellRequestKey, "")) if self.__db.IsRequestProcessing(reqNum): self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.RequestAlreadyAcceptedKey)) return req = self.__db.GetRawRequest(reqNum) reqType = db.RequestType(req[2]) buyer = self.username if reqType == db.RequestType.Sell else req[ 1] seller = req[ 1] if reqType == db.RequestType.Sell else self.username self.__db.AddProcessingRequest(reqNum, seller, buyer) reqUserChatId = self.__db.GetUserChatId(req[1]) keyboard = InlineKeyboardMarkup(row_width=1) keyboard.row( InlineKeyboardButton( ld.get_translate(self.__db, self.username, ld.AcceptKey), callback_data="{0}{1}".format(ld.AcceptKey, reqNum))) print("{0}({1}) sent accept message to user {2}({3})".format( self.username, self.__chatId, req[1], reqUserChatId)) self.__bot.send_message(reqUserChatId, ld.get_translate( self.__db, req[1], ld.RequestWasAcceptedKey).format( reqNum, self.username), reply_markup=keyboard) self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.RequestWasSentKey)) self.__StartRequestAcceptTimer(reqNum) except Exception as ex: print("Exception during accepting request: " + str(ex)) elif msg.startswith(ld.AcceptKey): try: print("{0} trying to accept request {1}".format( self.username, msg)) reqNum = int(msg.replace(ld.AcceptKey, "")) processingReq = self.__db.GetProcessingRequest(reqNum) if len(processingReq) == 0: print("Request is no longer exists") self.__bot.send_message( self.__chatId, ld.get_translate(self.__db, self.username, ld.AcceptRequestNoLongerActiveKey)) return seller = processingReq[1] buyer = processingReq[2] sellerChatId = self.__db.GetUserChatId(seller) buyerChatId = self.__db.GetUserChatId(buyer) print("Send Finish Accept message to user {0}, chatId {1}". format(seller, sellerChatId)) self.__bot.send_message( sellerChatId, ld.get_translate( self.__db, seller, ld.RequestHasBeenAcceptedBothSidesKey).format( reqNum, buyer)) print("Send Finish Accept message to user {0}, chatId {1}". format(buyer, buyerChatId)) self.__bot.send_message( buyerChatId, ld.get_translate( self.__db, buyer, ld.RequestHasBeenAcceptedBothSidesKey).format( reqNum, seller)) self.__DeleteProcessingRequest(reqNum) self.__db.DeleteReqWithId(reqNum) except: print("Exception during accepting request")
def __getLocalizedRequestType(self, reqType: RequestType, callUser): if reqType == RequestType.Buy: return ld.get_translate(self, callUser, ld.BuyKey).lower() else: return ld.get_translate(self, callUser, ld.SellKey).lower()
def Start(self): self.currentStep = RequestSteps.Start self.__currentPage = 0 self.__deleteAllReqKeyboard() isNotifEnabled = self.__db.IsNotificationsRowExistForUser( self.username) keyboard = InlineKeyboardMarkup(row_width=5) keyboard.row( InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.BuyKey), callback_data=ld.BuyKey), InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.SellKey), callback_data=ld.SellKey)) keyboard.row( InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.ShowMyReqKey), callback_data=ld.ShowMyReqKey), InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.ShowAllReqKey), callback_data=ld.ShowAllReqKey)) keyboard.row( InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.VoteKey), callback_data=ld.VoteKey), InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.UnvoteKey), callback_data=ld.UnvoteKey), InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.EscrowListKey), callback_data=ld.EscrowListKey)) btnCallbackData = ld.DisableNotifKey if isNotifEnabled else ld.EnableNotifKey keyboard.row( InlineKeyboardButton(ld.get_translate(self.__db, self.username, btnCallbackData), callback_data=btnCallbackData)) keyboard.row( InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.EnglishKey), callback_data=ld.EnglishKey), InlineKeyboardButton(ld.get_translate(self.__db, self.username, ld.RussianKey), callback_data=ld.RussianKey)) self.__deleteStartMessage() reply = self.__bot.send_message(self.__chatId, ld.get_translate( self.__db, self.username, ld.StartMessageKey), parse_mode="HTML", reply_markup=keyboard) self.__startMsgId = reply.message_id