def stats_exchange_received(self, update, context): """Ask which market stats are wanted for""" if update.message.text.lower() == "done": return None if update.message.text.lower() == "cancel": update.message.reply_text("Operation Cancelled", reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END if update.message.text in ("Coinbase Pro", "Kucoin", "Binance"): self.exchange = update.message.text.lower() if update.message.text == "Coinbase Pro": self.exchange = "coinbasepro" else: if self.exchange == "": update.message.reply_text("Invalid Exchange Entered!") self.statsrequest(update, context) return None update.message.reply_text( "Which market/pair do you want stats for?", reply_markup=ReplyKeyboardRemove(), ) return TYPING_REPLY
def newbot_start(self, update, context, startmethod: str = "telegram") -> None: """start bot - start bot if want""" if not self._checkifallowed(context._user_id_and_data[0], update): return None if update.message.text == "No": update.message.reply_text("Command Complete, have a nice day.", reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END if (self.helper.startProcess(self.pair, self.exchange, self.overrides, startmethod) == False): update.message.reply_text( f"{self.pair} is already running, no action taken.", reply_markup=ReplyKeyboardRemove(), ) else: if startmethod != "scanner": update.message.reply_text( f"{self.pair} crypto bot Starting", reply_markup=ReplyKeyboardRemove(), ) update.message.reply_text("Command Complete, have a nice day.", reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END
def ExceptionAdd(self, update, context): """start bot - save if required ask if want to start""" if not self._checkifallowed(context._user_id_and_data[0], update): return None self._answer_which_pair(update) self.helper.read_data() if "scannerexceptions" not in self.helper.data: self.helper.data.update({"scannerexceptions": {}}) if not self.pair in self.helper.data["scannerexceptions"]: self.helper.data["scannerexceptions"].update({self.pair: {}}) self.helper.write_data() update.message.reply_text( f"{self.pair} Added to Scanner Exception List \u2705", reply_markup=ReplyKeyboardRemove(), ) else: update.message.reply_text( f"{self.pair} Already on exception list", reply_markup=ReplyKeyboardRemove(), ) return ConversationHandler.END
def _answer_which_pair(self, update, context) -> bool: if update.message.text.lower() == "cancel": self.helper.send_telegram_message(update, "Operation Cancelled", ReplyKeyboardRemove(), context) return ConversationHandler.END if self.exchange in ("coinbasepro", "kucoin"): p = re.compile(r"^[0-9A-Z]{1,20}\-[1-9A-Z]{2,5}$") if not p.match(update.message.text): self.helper.send_telegram_message(update, "Invalid market format", ReplyKeyboardRemove(), context) return False elif self.exchange == "binance": p = re.compile(r"^[A-Z0-9]{4,25}$") if not p.match(update.message.text): self.helper.send_telegram_message(update, "Invalid market format.", ReplyKeyboardRemove(), context) return False self.pair = update.message.text return True
def handle_next_action(self, bot: Bot, update: Update, user_data): if update.message.text == self.NEXT_ACTION_KEYBOARD["NEUE_REISE"]: update.message.reply_text( "Okay, noch eine Reise.\n\n" "An welchem Tag bist du unterwegs? (Verwende nach Möglichkeit das Format <em>dd.mm.yyyy</em>)", parse_mode=ParseMode.HTML, reply_markup=ReplyKeyboardRemove()) return self.WAIT_FOR_DATE elif update.message.text == self.NEXT_ACTION_KEYBOARD["FERTIG"]: update.message.reply_text("Okay, das war's dann.", reply_markup=ReplyKeyboardRemove()) return self.END
def handle_hometown(self, bot: Bot, update: Update, user_data): message = update.message # type: Message if message.location: hometown = get_city(message.location.latitude, message.location.longitude) else: hometown = message.text user = User.update_or_create( attributes={"telegram_user_id": message.from_user.id}, values={ "telegram_username": message.from_user.username, "hometown": hometown }) text = "Okay. Du wohnst in <strong>%s</strong>.\n\n" % hometown opportunities = Opportunity.for_city(user.hometown) if opportunities.count() == 0: text += "Aktuell sind keine Bestellmöglichkeiten verfügbar. Ich werde dich benachrichtigen, wenn es soweit ist." else: text += "@marudor kommt an folgenden Tagen in deine Stadt:\n" for op in opportunities: text += "<strong>%s</strong>: Bestelle mit /order_%s\n" % ( op.date.strftime("%d.%m.%Y"), op.id) if "new_user" in user_data: del user_data["new_user"] text += self.generate_command_intro() update.message.reply_text(text, parse_mode=ParseMode.HTML, reply_markup=ReplyKeyboardRemove()) return self.END
def start(update, _): """ Starts a conversation about quiz creation. Welcomes the user and asks for the type of the first question. """ logger.info('[%s] Creation initialized', update.message.from_user.username) if update.message.from_user.id in userDict: # user is in the middle of a quiz and cant attempt to a second one logger.info( '[%s] Creation canceled, because the user is in the middle of a creation.', update.message.from_user.username) update.message.reply_text( "You're in the middle of a creation 😉 " "You can't create a second one at the same time 😁\n" 'If you want to cancel your creation, enter /cancelCreate.', reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END # Init Quiz for user userDict[update.message.from_user.id] = { 'quiz': Quiz(update.message.from_user.username) } # Asks for type of first question list_question = [[el] for el in list(dict_question_types.keys())] update.message.reply_text( "Hi 😃 Let's create a new quiz!\n" "What type of question should the first one be?\n" 'If you want to cancel your creation, enter /cancelCreate.', reply_markup=ReplyKeyboardMarkup(list_question, one_time_keyboard=True)) return 'ENTER_TYPE'
def setcommands(self, update, context) -> None: command = [ BotCommand("controlpanel", "show command buttons"), BotCommand("cleandata", "clean JSON data files"), BotCommand("addexception", "add pair to scanner exception list"), BotCommand("removeexception", "remove pair from scanner exception list"), BotCommand("startscanner", "start auto scan high volume markets and start bots"), BotCommand("stopscanner", "stop auto scan high volume markets"), BotCommand("addnew", "add and start a new bot"), BotCommand("deletebot", "delete bot from startbot list"), BotCommand("margins", "show margins for all open trades"), BotCommand("trades", "show closed trades"), BotCommand("stats", "show exchange stats for market/pair"), BotCommand("help", "show help text") # BotCommand("showinfo", "show all running bots status"), # BotCommand("showconfig", "show config for selected exchange"), # BotCommand("startbots", "start all or selected bot"), # BotCommand("stopbots", "stop all or the selected bot"), # BotCommand("pausebots", "pause all or selected bot"), # BotCommand("resumebots", "resume paused bots"), # BotCommand("buy", "manual buy"), # BotCommand("sell", "manual sell"), ] ubot = Bot(self.token) ubot.set_my_commands(command) update.message.reply_text( "<i>Bot Commands Created</i>", parse_mode="HTML", reply_markup=ReplyKeyboardRemove(), )
def cancel(bot, update): user = update.message.from_user logger.info('User %s canceled the conversation.' % user.first_name) update.message.reply_text('Из этой игры нельзя выйти!', reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END
def stats_pair_received(self, update, context): """Show stats for selected exchange and market""" if update.message.text.lower() == "done": return None if update.message.text.lower() == "cancel": self.helper.send_telegram_message(update, "Operation Cancelled", ReplyKeyboardRemove(), context=context) return ConversationHandler.END if self.exchange in ("coinbasepro", "kucoin"): p = re.compile(r"^[0-9A-Z]{1,20}\-[1-9A-Z]{2,5}$") if not p.match(update.message.text): self.helper.send_telegram_message( update, "Invalid market format", ReplyKeyboardRemove(), context=context, ) self.stats_exchange_received(update, context) return None elif self.exchange == "binance": p = re.compile(r"^[A-Z0-9]{4,25}$") if not p.match(update.message.text): self.helper.send_telegram_message( update, "Invalid market format", ReplyKeyboardRemove(), context=context, ) self.stats_exchange_received(update, context) return None self.pair = update.message.text self.helper.send_telegram_message( update, "<i>Gathering Stats, please wait...</i>", context=context) output = self.helper.start_process(self.pair, self.exchange, "--stats --live 1", "telegram", True) self.helper.send_telegram_message(update, output, context=context) return ConversationHandler.END
def test(bot, update): # buttons = ReplyKeyboardMarkup([ # [KeyboardButton('Телефон', request_contact=True), KeyboardButton('Локация', request_location=True)], # ]) bot.sendMessage( text=pp.pformat(update.to_json()), chat_id=update.message.chat_id, reply_markup=ReplyKeyboardRemove(), # parse_mode='Markdown' )
def remove(update: Update, context: CallbackContext): """ method to handle /remove command to remove the keyboard and return back to text reply """ reply_markup = ReplyKeyboardRemove() # sending the reply so as to remove the keyboard update.message.reply_text(text="I'm back.", reply_markup=reply_markup) pass
def remove(update: Update, context: CallbackContext): """ method to handle /remove command to remove the keyboard and return back to text reply """ # making a reply markup to remove keyboard # documentation: https://python-telegram-bot.readthedocs.io/en/stable/telegram.replykeyboardremove.html reply_markup = ReplyKeyboardRemove() # sending the reply so as to remove the keyboard update.message.reply_text(text="I'm back.", reply_markup=reply_markup) pass
def newbot_start(self, update, context, startmethod: str = "telegram") -> None: """start bot - start bot if want""" if not self._check_if_allowed(context._user_id_and_data[0], update): # pylint: disable=protected-access return None if update.message.text == "No": self.helper.send_telegram_message( update, "Command Complete, have a nice day.", ReplyKeyboardRemove(), context, ) return ConversationHandler.END if (self.helper.start_process(self.pair, self.exchange, self.overrides, startmethod) is False): self.helper.send_telegram_message( update, f"{self.pair} is already running, no action taken.", ReplyKeyboardRemove(), context, ) else: if startmethod != "scanner": self.helper.send_telegram_message( update, f"{self.pair} crypto bot Starting", ReplyKeyboardRemove(), context, ) self.helper.send_telegram_message( update, "Command Complete, have a nice day.", ReplyKeyboardRemove(), context) return ConversationHandler.END
def cancel(update, _): """ Cancels a creation ofa quiz by deleting the users' entries. """ logger.info('[%s] Creation canceled by user', update.message.from_user.username) # Delete user data userDict.pop(update.message.from_user.id) update.message.reply_text( "I canceled the creation process. See you next time. 🙋♂️", reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END
def ExceptionAdd(self, update, context): """start bot - save if required ask if want to start""" if not self._check_if_allowed(context._user_id_and_data[0], update): # pylint: disable=protected-access return None self.helper.logger.info("called ExceptionAdd") self._answer_which_pair(update, context) self.helper.read_data() if "scannerexceptions" not in self.helper.data: self.helper.data.update({"scannerexceptions": {}}) if not self.pair in self.helper.data["scannerexceptions"]: write_ok, try_count = False, 0 while not write_ok and try_count <= 5: try_count += 1 self.helper.data["scannerexceptions"].update({self.pair: {}}) write_ok = self.helper.write_data() if not write_ok: sleep(1) self.helper.send_telegram_message( update, f"{self.pair} Added to Scanner Exception List \u2705", ReplyKeyboardRemove(), context, ) else: self.helper.send_telegram_message( update, f"{self.pair} Already on exception list", ReplyKeyboardRemove(), context, ) return ConversationHandler.END
def remove_reservation_cron_complete(update: Update, _: CallbackContext) -> int: global _IS_ACTIVATED global _CRON_INTERACTIONS if not _authenticate(update): return CmdStatus.UNAUTHORISED_USER _LOGGER.debug("Received new request: remove_reservation_cron_complete") if _IS_ACTIVATED: try: cron_id = update.message.text cron_id = int(cron_id) except Exception: cron_id = None if cron_id is None or not (0 <= cron_id < _CRON_INTERACTIONS.get_num_active_crons()): update.message.reply_text( "Error: Invalid cron id. Value must be between 0 and " + str(_CRON_INTERACTIONS.get_num_active_crons())) else: try: _CRON_INTERACTIONS.cron_delete(cron_id) except Exception: update.message.reply_text( "ERROR: Internal error creating cron with id " + str(cron_id), reply_markup=ReplyKeyboardRemove()) else: update.message.reply_text("Cron with id " + str(cron_id) + " has been erased", reply_markup=ReplyKeyboardRemove()) else: update.message.reply_text(_INACTIVE_MSG) return ConversationHandler.END
def _answer_which_pair(self, update) -> bool: if update.message.text.lower() == "cancel": update.message.reply_text("Operation Cancelled", reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END if self.exchange in ("coinbasepro", "kucoin"): p = re.compile(r"^[1-9A-Z]{2,20}\-[1-9A-Z]{2,5}$") if not p.match(update.message.text): update.message.reply_text("Invalid market format", reply_markup=ReplyKeyboardRemove()) # self.newbot_exchange(update, context) return False elif self.exchange == "binance": p = re.compile(r"^[A-Z0-9]{5,13}$") if not p.match(update.message.text): update.message.reply_text("Invalid market format.", reply_markup=ReplyKeyboardRemove()) # self.newbot_exchange(update, context) return False self.pair = update.message.text return True
def stats_pair_received(self, update, context): """Show stats for selected exchange and market""" if update.message.text.lower() == "done": return None if update.message.text.lower() == "cancel": update.message.reply_text("Operation Cancelled", reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END if self.exchange == "coinbasepro" or self.exchange == "kucoin": p = re.compile(r"^[1-9A-Z]{2,20}\-[1-9A-Z]{2,5}$") if not p.match(update.message.text): update.message.reply_text("Invalid market format", reply_markup=ReplyKeyboardRemove()) self.stats_exchange_received(update, context) return None elif self.exchange == "binance": p = re.compile(r"^[A-Z0-9]{5,13}$") if not p.match(update.message.text): update.message.reply_text("Invalid market format.", reply_markup=ReplyKeyboardRemove()) self.stats_exchange_received(update, context) return None self.pair = update.message.text update.message.reply_text("<i>Gathering Stats, please wait...</i>", parse_mode="HTML") output = self.helper.startProcess(self.pair, self.exchange, "--stats", "telegram", True) update.message.reply_text(output, parse_mode="HTML") return ConversationHandler.END
def handle_hw(bot, update: Update, user_data, prev_task: QueueTask = None): user = get_user(update.message) # TODO: store in database user_data.setdefault('style', Style()) if not user: update.message.reply_text('Not logged in') return ConversationHandler.END user_data['user'] = user tasks: Tasks = user_data.get('tasks') if not tasks or len(tasks.order) < 8: update.message.reply_text('Запрашиваем данные...', reply_markup=ReplyKeyboardRemove()) q = [QueueTask(t) for t in get_check_queue(user.sid, 8)] futures = tasks.futures if tasks else {} futures.update({ t.id: get_issue_async(user.sid, t.id) for t in q if t.id not in futures }) tasks = Tasks({t.id: t for t in q}, q, futures) user_data['tasks'] = tasks else: q = tasks.order if prev_task and prev_task.id in tasks.mapping: del tasks.mapping[prev_task.id] del tasks.futures[prev_task.id] tasks.order.remove(prev_task) if not q: update.message.reply_text('Ура! Домашки проверены' if prev_task else 'Пока что домашек нет...', reply_markup=greeting_markup) return ConversationHandler.END tasks = [('task#' + str(t.id), '{} -- {}'.format(t.task_title, t.student_name)) for t in q[:7]] keyboard = [[Button(t, callback_data=i)] for i, t in tasks] markup = InlineKeyboardMarkup(keyboard, one_time_keyboard=True) update.message.reply_text('Выберите задание на проверку', reply_markup=markup) return State.task_choose
def setup_balance_alert_cancel(update: Update, _: CallbackContext) -> int: global _IS_ACTIVATED global _CREATION_CRON_INFO if not _authenticate(update): return CmdStatus.UNAUTHORISED_USER _LOGGER.debug("Cancelled setup_balance_alert") if _IS_ACTIVATED: update.message.reply_text( "Setting up balance alert process aborted. Nothing was updated.", reply_markup=ReplyKeyboardRemove()) else: update.message.reply_text(_INACTIVE_MSG) return ConversationHandler.END
def remove_reservation_cron_cancel(update: Update, _: CallbackContext) -> int: global _IS_ACTIVATED global _CREATION_CRON_INFO if not _authenticate(update): return CmdStatus.UNAUTHORISED_USER _LOGGER.debug("Cancelled remove_reservation_cron") if _IS_ACTIVATED: _CREATION_CRON_INFO = None update.message.reply_text( "Removing reservation cron process aborted. Nothing was updated.", reply_markup=ReplyKeyboardRemove()) else: update.message.reply_text(_INACTIVE_MSG) return ConversationHandler.END
def newbot_market(self, update, context): """start bot - ask for overrides if none required ask to save bot""" if not self._checkifallowed(context._user_id_and_data[0], update): return None if update.message.text == "No": reply_keyboard = [["Yes", "No"]] markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True) update.message.reply_text("Do you want to save this?", reply_markup=markup) return SAVE update.message.reply_text( "Tell me any other commandline overrides to use?", reply_markup=ReplyKeyboardRemove(), ) return OVERRIDES
def _answer_which_exchange(self, update) -> bool: """start bot validate exchange and ask which market/pair""" if update.message.text.lower() == "cancel": update.message.reply_text("Operation Cancelled", reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END if (update.message.text == "Coinbase Pro" or update.message.text == "Kucoin" or update.message.text == "Binance"): self.exchange = update.message.text.lower() if update.message.text == "Coinbase Pro": self.exchange = "coinbasepro" else: if self.exchange == "": update.message.reply_text("Invalid Exchange Entered!") # self.newbot_request(update, context) return False return True
def enter_quiz_name(update, context): """ After entering the name of the quiz, it looks up if the quiz name is occupied. Otherwise is saves the quiz. """ logger.info('[%s] Completed quiz creation', update.message.from_user.username) user_id = update.message.from_user.id quizname = update.message.text # Bot is typing during database query context.bot.send_chat_action(chat_id=update.effective_message.chat_id, action=ChatAction.TYPING) # Query for question with input name user_col = db[update.message.from_user.username] if not user_col.find_one({'quizname': quizname}) is None: # Quiz with quizname already exists update.message.reply_text( "Sorry. You already have a quiz named {} 😕\nPlease try something else" .format(quizname)) logger.info('[%s] Quiz with name "%s" already exists', update.message.from_user.username, update.message.text) return 'ENTER_QUIZ_NAME' # Insert Quiz with quizname in database user_col.insert_one({ 'quizname': quizname, 'quizinstance': pickle.dumps(userDict[user_id]['quiz']) }) update.message.reply_text( "Great! 🥳 I saved your new quiz." "You can attempt to it by the name {}.".format(quizname), reply_markup=ReplyKeyboardRemove()) logger.info('[%s] Quiz saved as "%s"', update.message.from_user.username, update.message.text) # Delete user data userDict.pop(update.message.from_user.id) return ConversationHandler.END
def set_user_opinion(bot, update): chat_id = update.message.chat_id message = update.message.text if message != state_left: username_get = update.message.chat.username first_name_get = update.message.chat.first_name last_name_get = update.message.chat.last_name bot.send_message( chat_id, "با سپاس نظر شما ثبت شد و در کوتاهترین زمان رسیدگی میگردد.", reply_markup=ReplyKeyboardRemove()) requests.post('http://127.0.0.1:8000/userOpinion/', json={ "user_opinion_id": chat_id, "user_opinion_text": message, "username": username_get, "first_name": first_name_get, "last_name": last_name_get }) set_user_state(chat_id, state_home_page) send_start_menu(bot, update)
def dealers_turn(self): if self.dealer.get_number_of_cards() < 2: card = None for _ in range(2): card = self.deck.pick_one_card() self.dealer.give_card(card) text = "" if self.game_type == self.PRIVATE_CHAT: text += translate("gameBegins", self.lang_id) + "\n" text += "\n*{}*\n\n{}, | -- |".format( translate("dealersCards", self.lang_id), str(card)) self.send_message(self.chat_id, text, parse_mode="Markdown", reply_markup=self.keyboard_running) else: output_text = translate("croupierDrew", self.lang_id) + "\n\n" while self.dealer.cardvalue <= 16: card = self.deck.pick_one_card() self.dealer.give_card(card) i = 0 for card in self.dealer.cards: if i == 0: output_text += str(card) else: output_text += " , " + str(card) i += 1 output_text += "\n\n{} {}".format( translate("cardvalueDealer", self.lang_id), self.dealer.cardvalue) self.send_message(self.chat_id, output_text, parse_mode="Markdown", reply_markup=ReplyKeyboardRemove()) self.evaluation()
def setup_reservation_cron_complete(update: Update, _: CallbackContext) -> int: global _IS_ACTIVATED global _CREATION_CRON_INFO global _CRON_INTERACTIONS if not _authenticate(update): return CmdStatus.UNAUTHORISED_USER _LOGGER.debug("Received new request: setup_reservation_cron_complete") if _IS_ACTIVATED: if _CREATION_CRON_INFO is None: update.message.reply_text( "Error: Please set up the game day, time, and duration first or restart the whole process" ) else: _CREATION_CRON_INFO["duration"] = update.message.text game_day = _CREATION_CRON_INFO["day"] game_start_time = _CREATION_CRON_INFO["start_time"] game_duration = _CREATION_CRON_INFO["duration"] try: _CRON_INTERACTIONS.cron_create(game_day=game_day, game_start_time=game_start_time, game_duration=game_duration) except Exception: update.message.reply_text( "Error: Internal exception creating job") else: _CREATION_CRON_INFO = None update.message.reply_text( "Your reservation cron has been created!\n" + "Every " + game_day + " at " + game_start_time + " for " + game_duration, reply_markup=ReplyKeyboardRemove()) else: update.message.reply_text(_INACTIVE_MSG) return ConversationHandler.END
def newbot_market(self, update, context): """start bot - ask for overrides if none required ask to save bot""" if not self._check_if_allowed(context._user_id_and_data[0], update): # pylint: disable=protected-access return None if update.message.text == "No": reply_keyboard = [["Yes", "No"]] mark_up = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True) self.helper.send_telegram_message(update, "Do you want to save this?", mark_up, context) return SAVE self.helper.send_telegram_message( update, "Tell me any other commandline overrides to use?", ReplyKeyboardRemove(), context, ) return OVERRIDES
def __init__(self, act: dict): self.original_dict = act self.id = act['id'] self.triggers = act['triggers'] self.data = act['data'] self.follow_up_action_id = None if 'follow_up_action_id' in act: self.follow_up_action_id = act['follow_up_action_id'] self.follow_up_action = None self.next_action_id = None if 'next_action_id' in act: self.next_action_id = act['next_action_id'] self.next_action = None self.markup = None if 'markup_type' in act: markup_type = act['markup_type'] if 'markup_data' in act: markup_string = act['markup_data'] # convert it to lists in list options = [[item for item in row.split(",")] for row in markup_string.split(":")] if markup_type == MarkupType.OneTimeReply: self.markup = ReplyKeyboardMarkup(options, one_time_keyboard=True) if markup_type == MarkupType.StaticReply: self.markup = ReplyKeyboardMarkup(options) elif act['markup_type'] == MarkupType.Remove: self.markup = ReplyKeyboardRemove() else: print( 'error 15' ) # act is not correct , markup_type exist and not 'Remove' but no markup_data