def start_over(update: Update, context: CallbackContext) -> int: query = update.callback_query query.answer() Logger.getInstance().info("L'utente " + context.user_data["username"] + " ha ricominciato la conversazione.") keyboard = [[ InlineKeyboardButton( "LINK", url="http://web.dmi.unict.it/corsi/l-31/programmi"), InlineKeyboardButton("Iniziamo!", callback_data=str(0)) ]] reply_markup = InlineKeyboardMarkup(keyboard) context.user_data["index_list_subject_length"] = 4 context.user_data["ratings"] = [] context.user_data["subject_names"] = [] Subjects.getInstance().init_array(context.user_data["ratings"], context.user_data["subject_names"]) query.edit_message_text( text= "Prima di iniziare è necessario che tu legga i programmi delle varie materie del 3° anno.\n" + "Questo è un passo fondamentale perché dopo ti verrà chiesto di valutarne alcuni!\n" + "Puoi cliccare nel bottone sottostante per raggiungere la pagina dei programmi.\n" + "Dopo aver letto tutto attentamente clicca su \"Iniziamo!\", ricorda che il range dei voti va da 1 (pessimo) a 5 (fantastico).", reply_markup=reply_markup) return 0
def rate_best_subject(update: Update, context: CallbackContext) -> int: context.user_data["rate_number"] = random.randint(0, 2) context.user_data["rate"] = 5 query = update.callback_query query.answer() context.user_data[ "index_list_subject"] = -context.user_data["index_list_subject_length"] reply_markup = InlineKeyboardMarkup( create_keyboard(context, 1, Subjects.getInstance().get_subjects())) query.edit_message_text( text= "In base ai programmi letti, qual è la materia che ha stimolato maggiormente la tua curiosità?", reply_markup=reply_markup) return 0
def rate_subject(query, context: CallbackContext) -> int: context.user_data["rate"] = random.choices( range(5), weights=[0.24, 0.34, 0.22, 0.10, 0.10], k=1)[0] + 1 context.user_data[ "index_list_subject"] = -context.user_data["index_list_subject_length"] reply_markup = InlineKeyboardMarkup( create_keyboard(context, 1, Subjects.getInstance().get_subjects())) query.edit_message_text(text="A quale materia daresti un voto pari a " + str(context.user_data["rate"]) + " in base al programma?", reply_markup=reply_markup) if (np.count_nonzero(np.array(context.user_data["ratings"])) > context.user_data["rate_number"]): return 1 return 0
def update_rating(index: str, context: CallbackContext) -> None: context.user_data["ratings"][int(index)] = context.user_data["rate"] Logger.getInstance().info("L'utente " + context.user_data["username"] + " ha dato un voto pari a " + str(context.user_data["rate"]) + " a " + Subjects.getInstance().get_subjects()[index] + ".")
def edit_question_private(update: Update, context: CallbackContext) -> int: message = update.message callback_query = update.callback_query if callback_query: text = "Begin" callback_query.answer() index = private_callback(callback_query.data) context.chat_data.clear() context.chat_data.update(index=index) callback_query.edit_message_text( context.bot_data.get("config").get("EDIT_QUESTION_PRIVATE").format( num=index + 1)) elif message: text = message.text if not context.chat_data.get("QUESTION"): context.chat_data.update(QUESTION=text) return_text = (context.bot_data.get("config").get( "EDIT_ANSWER_PRIVATE").format(text=text)) elif not context.chat_data.get("ANSWER"): context.chat_data.update(ANSWER=text) return_text = (context.bot_data.get("config").get( "EDIT_WRONG_PRIVATE").format(text=text)) else: if not context.chat_data.get("WRONG"): context.chat_data["WRONG"] = list() context.chat_data.get("WRONG").append(text) return_text = (context.bot_data.get("config").get( "EDIT_MORE_WRONG_PRIVATE").format(text=text)) message.reply_text( context.bot_data.get("config").get("EDIT_PRIVATE").format( text=return_text)) logger.info(f"Private: Edit question {text}") return QUESTION_EDIT
def dispatch_error(self, update: Optional[HandlerArg], error: Exception, promise: Promise = None) -> None: """Dispatches an error. Args: update (:obj:`str` | :class:`telegram.Update` | None): The update that caused the error error (:obj:`Exception`): The error that was raised. promise (:class:`telegram.utils.Promise`, optional): The promise whose pooled function raised the error. """ async_args = None if not promise else promise.args async_kwargs = None if not promise else promise.kwargs if self.error_handlers: for callback, run_async in self.error_handlers.items(): if self.use_context: context = CallbackContext.from_error(update, error, self, async_args=async_args, async_kwargs=async_kwargs) if run_async: self.run_async(callback, update, context, update=update) else: callback(update, context) else: if run_async: self.run_async(callback, self.bot, update, error, update=update) else: callback(self.bot, update, error) else: self.logger.exception( 'No error handlers are registered, logging exception.', exc_info=error)
def first_receiver(update: Update, context: CallbackContext): context.user_data['receivers'] = list() context.user_data['receivers'].append(update.message.text) update.message.reply_text( """Tell me any another receiver or /quit.""" ) return CONTINUE
def cities(update: Update, context: CallbackContext) -> None: # TODO мб упростить функцию и разнести на более мелкие if context.args and len(context.args) == 1: city = context.args[0].lower() if context.user_data.get('used_cities'): if city[0] not in CITIES or city not in CITIES[city[0]]: msg = f"Такого города не знаю, введите город на букву {context.user_data['last_letter']}" update.message.reply_text(msg) elif city in context.user_data['used_cities']: update.message.reply_text('Увы такой город уже был') else: context.user_data['used_cities'].add(city) bot_city = next_city(last_letter(city), context.user_data['used_cities']) if not bot_city: game_over(update, context.user_data['used_cities'], last_letter(city)) return context.user_data['used_cities'].add(bot_city) msg_part_1 = f'Мой город: {bot_city.title()}\n' context.user_data['last_letter'] = last_letter( bot_city).upper() msg_part_2 = f'Тебе на букву {context.user_data["last_letter"]}' update.message.reply_text(msg_part_1 + msg_part_2) elif city[0] not in CITIES or city not in CITIES[city[0]]: update.message.reply_text("Такого города не знаю") else: context.user_data['used_cities'] = set() context.user_data['used_cities'].add(city) bot_city = next_city(last_letter(city), context.user_data['used_cities']) context.user_data['used_cities'].add(bot_city) msg_part_1 = f'Мой город: {bot_city.title()}\n' context.user_data['last_letter'] = last_letter(bot_city).upper() msg_part_2 = f'Тебе на букву {context.user_data["last_letter"]}' update.message.reply_text(msg_part_1 + msg_part_2) elif context.args: msg = "Тебе следует вводить название одного города.\nВо вводе только один пробел после /cities" update.message.reply_text(msg) elif context.user_data.get('used_cities'): update.message.reply_text( f"Введи /cities и город на букву {context.user_data['last_letter']}" ) else: update.message.reply_text( f"Для старта игры введи /cities и любой существующий в этом мире город" )
def get_username(update: Update, context: Context): username = update.message.text context.user_data['username'] = username context.bot.send_message( chat_id=update.effective_chat.id, text="Password:" ) return states.GET_PASSWORD
def process_update(self, update: Union[str, Update, TelegramError]) -> None: """Processes a single update. Args: update (:obj:`str` | :class:`telegram.Update` | :class:`telegram.TelegramError`): The update to process. """ # An error happened while polling if isinstance(update, TelegramError): try: self.dispatch_error(None, update) except Exception: self.logger.exception( 'An uncaught error was raised while handling the error.') return context = None for group in self.groups: try: for handler in self.handlers[group]: check = handler.check_update(update) if check is not None and check is not False: if not context and self.use_context: context = CallbackContext.from_update(update, self) handler.handle_update(update, self, check, context) # If handler runs async updating immediately doesn't make sense if not handler.run_async: self.update_persistence(update=update) break # Stop processing with any other handler. except DispatcherHandlerStop: self.logger.debug( 'Stopping further handlers due to DispatcherHandlerStop') self.update_persistence(update=update) break # Dispatch any error. except Exception as e: try: self.dispatch_error(update, e) except DispatcherHandlerStop: self.logger.debug('Error handler stopped further handlers') break # Errors should not stop the thread. except Exception: self.logger.exception( 'An uncaught error was raised while handling the error.' )
def handle_expired_token(update: Update, context: Context, func): username, password = context.user_data['username'], context.user_data['password'] r = requests.post( url= constants.SERVER_URL + "authenticate", json= {"username": username, "password": password} ) if r.status_code != 200: return send_connection_error_msg(update, context) context.user_data['token'] = r.json()['token'] return func(update, context)
def ask_email_content(update: Update, context: CallbackContext): print(update.message.text) no=int(update.message.text)-1 templates = get_email_templates(update.effective_chat.id) document={} for i,t in zip(range(templates.count()),templates): if i==no: document=t context.user_data['document'] = document update.message.reply_text("Please specify mail content") return SEND
def ask_email_name(update: Update, context: CallbackContext): templates = get_email_templates(update.effective_chat.id) context.user_data['templates']=templates l=list() for i,t in zip(range(1,templates.count()+1),templates): l.append("{i}. {t}".format(i=i,t=t['email_name'])) l="\n".join(l) update.message.reply_text("Please choose one of the following templates\n"+l) return CONTENT
def schedule_first(update: Update, context: CallbackContext) -> int: """Process the start datetime to schedule the message from. Args: update (Update): Update from telegram context (CallbackContext): CallbackContext for the update Returns: int: The next state in the conversation """ if update.message.text.lower() == "now": date_object = None else: try: date_object = datetime.strptime(update.message.text, "%Y-%m-%d %H:%M:%S") date_object = date_object.replace(tzinfo=IST) if date_object < datetime.now(IST): update.message.reply_text( "Hello Respected Sir/Madamji,\n\nI am only a simple bot. I cannot do this time-travel stuffs. " + "So kindly give me a date and time in the future only. " + "Or if you want to schedule it immediately, reply 'now'. " + "Hoping for a fast (and correct) reply.\n\n" + "With fewer and fewer regards,\nGoodMorningBot", parse_mode="markdown", ) return FIRST except ValueError: update.message.reply_text( "Hello Respected Sir/Madamji,\n\nI _specifically_ mentioned one format no? Still why are you doing " + "such stupid things. Please please please give me a date and time in the yyyy-mm-dd HH:MM:SS format only. " + "Or if you want to schedule it immediately, reply 'now'. " + "Hoping for a fast (and correct) reply.\n\n" + "With fewer and fewer regards,\nGoodMorningBot", parse_mode="markdown", ) return FIRST context.user_data[FIRST] = date_object update.message.reply_text( "Hello Respected Sir/Madamji,\n\nThank you for sending the start date. Please give me an *end date* also. " + "Use the same yyyy-mm-dd HH:MM:SS format again. Or if you want it to keep going forever, reply 'never'.\n\n" + "God bless,\nGoodMorningBot", parse_mode="markdown", ) return LAST
def run(self, dispatcher: 'Dispatcher') -> None: """Executes the callback function independently of the jobs schedule.""" try: if dispatcher.use_context: self.callback(CallbackContext.from_job(self, dispatcher)) else: self.callback(dispatcher.bot, self) # type: ignore[arg-type,call-arg] except Exception as e: try: dispatcher.dispatch_error(None, e) # Errors should not stop the thread. except Exception: dispatcher.logger.exception('An error was raised while processing the job and an ' 'uncaught error was raised while handling the error ' 'with an error_handler.')
def dispatch_error(self, update, error): """Dispatches an error. Args: update (:obj:`str` | :class:`telegram.Update` | None): The update that caused the error error (:obj:`Exception`): The error that was raised. """ if self.error_handlers: for callback in self.error_handlers: if self.use_context: callback(update, CallbackContext.from_error(update, error, self)) else: callback(self.bot, update, error) else: self.logger.exception( 'No error handlers are registered, logging exception.', exc_info=error)
def handle_update(self, update, dispatcher, check_result): """ This method is called if it was determined that an update should indeed be handled by this instance. Calls :attr:`self.callback` along with its respectful arguments. To work with the :class:`telegram.ext.ConversationHandler`, this method returns the value returned from ``self.callback``. Note that it can be overridden if needed by the subclassing handler. Args: update (:obj:`str` | :class:`telegram.Update`): The update to be handled. dispatcher (:class:`telegram.ext.Dispatcher`): The calling dispatcher. check_result: The result from :attr:`check_update`. """ if dispatcher.use_context: context = CallbackContext.from_update(update, dispatcher) self.collect_additional_context(context, update, dispatcher, check_result) return self.callback(update, context) else: optional_args = self.collect_optional_args(dispatcher, update, check_result) return self.callback(dispatcher.bot, update, **optional_args)
def schedule_interval(update: Update, context: CallbackContext) -> int: """Process the interval at which the message is to be scheduled. Args: update (Update): Update from telegram context (CallbackContext): CallbackContext for the update Returns: int: The next state in the conversation """ context.user_data[INTERVAL] = int(update.message.text) update.message.reply_text( "Hello Respected Sir/Madamji,\n\nThank you for sending the interval data. When should I start sending " + "these greeting messages? Please give me *the start date and time in the yyyy-mm-dd HH:MM:SS format* " + " and I will start sending it then. Or if you want me to start now itself, reply 'now'.\n\n" + "With warmest regards,\nGoodMorningBot", parse_mode="markdown", ) return FIRST
def schedule_message(update: Update, context: CallbackContext) -> int: """Process the greeting message to be scheduled. Args: update (Update): Update from telegram context (CallbackContext): CallbackContext for the update Returns: int: The next state in the conversation """ context.user_data[MESSAGE] = update.message.text update.message.reply_text( "Hello Respected Sir/Madamji,\n\nThanks for sending me the greeting message. " + "I also need *the interval (in seconds)* at which you want to send the above-mentioned " + "greeting. Please type in that as well. Hoping for a quick reply.\n\n" + "With warmest regards,\nGoodMorningBot", parse_mode="markdown", ) return INTERVAL
def login_to_server(update: Update, context: Context): context.bot.send_message( chat_id=update.effective_chat.id, text="Connecting to server..." ) username, password = context.user_data['username'], context.user_data['password'] r = requests.post( url= constants.SERVER_URL + "authenticate", json= {"username": username, "password": password} ) code = r.status_code if code == 200: context.user_data['token'] = r.json()['token'] context.bot.send_message( chat_id=update.effective_chat.id, text="Connected successfully." ) logger.info(update.effective_user.username + " logged in. username: "******""" کدوم کارگاه؟ """, reply_markup=keyboards.field_selection() ) return states.SELECT_FIELD elif code == 401: context.bot.send_message( chat_id=update.effective_chat.id, text="Wrong Username or Password. Use /start command to try again." ) return states.END else: context.bot.send_message( chat_id=update.effective_chat.id, text="Can't connect to server! try again using /start command." ) return states.END
def process_update(self, update): """Processes a single update. Args: update (:obj:`str` | :class:`telegram.Update` | :class:`telegram.TelegramError`): The update to process. """ def persist_update(update): """Persist a single update. Args: update (:class:`telegram.Update`): The update to process. """ if self.persistence and isinstance(update, Update): if self.persistence.store_bot_data: try: self.persistence.update_bot_data(self.bot_data) except Exception as e: try: self.dispatch_error(update, e) except Exception: message = 'Saving bot data raised an error and an ' \ 'uncaught error was raised while handling ' \ 'the error with an error_handler' self.logger.exception(message) if self.persistence.store_chat_data and update.effective_chat: chat_id = update.effective_chat.id try: self.persistence.update_chat_data( chat_id, self.chat_data[chat_id]) except Exception as e: try: self.dispatch_error(update, e) except Exception: message = 'Saving chat data raised an error and an ' \ 'uncaught error was raised while handling ' \ 'the error with an error_handler' self.logger.exception(message) if self.persistence.store_user_data and update.effective_user: user_id = update.effective_user.id try: self.persistence.update_user_data( user_id, self.user_data[user_id]) except Exception as e: try: self.dispatch_error(update, e) except Exception: message = 'Saving user data raised an error and an ' \ 'uncaught error was raised while handling ' \ 'the error with an error_handler' self.logger.exception(message) # An error happened while polling if isinstance(update, TelegramError): try: self.dispatch_error(None, update) except Exception: self.logger.exception( 'An uncaught error was raised while handling the error') return context = None for group in self.groups: try: for handler in self.handlers[group]: check = handler.check_update(update) if check is not None and check is not False: if not context and self.use_context: context = CallbackContext.from_update(update, self) handler.handle_update(update, self, check, context) persist_update(update) break # Stop processing with any other handler. except DispatcherHandlerStop: self.logger.debug( 'Stopping further handlers due to DispatcherHandlerStop') persist_update(update) break # Dispatch any error. except Exception as e: try: self.dispatch_error(update, e) except DispatcherHandlerStop: self.logger.debug('Error handler stopped further handlers') break # Errors should not stop the thread. except Exception: self.logger.exception( 'An error was raised while processing the update and an ' 'uncaught error was raised while handling the error ' 'with an error_handler')
def _build_args(self, job: 'Job') -> List[Union[CallbackContext, 'Bot', 'Job']]: if self._dispatcher.use_context: return [CallbackContext.from_job(job, self._dispatcher)] return [self._dispatcher.bot, job]
# # handle all other telegram related errors logging.basicConfig( filename='bot.log', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.ERROR) # logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) if __name__ == '__main__': updater = Updater(conf.TOKEN, use_context=True, request_kwargs=conf.REQUEST_KWARGS) dispatcher = updater.dispatcher context = CallbackContext(dispatcher) updater.dispatcher.add_handler(CommandHandler('start', start)) updater.dispatcher.add_handler(CommandHandler('restart', start)) updater.dispatcher.add_handler(CommandHandler('help', help)) updater.dispatcher.add_error_handler(error_callback) # updater.dispatcher.add_handler(CallbackQueryHandler(button)) # updater.dispatcher.add_handler(MessageHandler(Filters.text, add_address)) # Start the Bot updater.start_polling() # Run the bot until the user presses Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT updater.idle()
def call_handler(updater, handler, message): update = Update(update_id=1, message=message) context = CallbackContext.from_update(update, updater.dispatcher) return handler(update, context)
def get_password(update: Update, context: Context): context.user_data['password'] = update.message.text.lower() return login_to_server(update, context)
def subject_name(update: Update, context: CallbackContext): context.user_data['subject_name'] = update.message.text update.message.reply_text( """Now specify receivers one by one. """ ) return RECEIVER
def email_name(update: Update, context: CallbackContext): context.user_data['email_name'] = update.message.text update.message.reply_text( """Tell me subject line you want to use for mail. """) return SUBJECT
def ask_signature(update: Update, context: CallbackContext): update.message.reply_text( """Please enter signature line by line """ ) context.user_data['signature']=list() return SIGNATURE
def run(self, dispatcher): """Executes the callback function.""" if dispatcher.use_context: self.callback(CallbackContext.from_job(self, dispatcher)) else: self.callback(dispatcher.bot, self)
def process_update(self, update: object) -> None: """Processes a single update and updates the persistence. Note: If the update is handled by least one synchronously running handlers (i.e. ``run_async=False``), :meth:`update_persistence` is called *once* after all handlers synchronous handlers are done. Each asynchronously running handler will trigger :meth:`update_persistence` on its own. Args: update (:class:`telegram.Update` | :obj:`object` | \ :class:`telegram.error.TelegramError`): The update to process. """ # An error happened while polling if isinstance(update, TelegramError): try: self.dispatch_error(None, update) except Exception: self.logger.exception( 'An uncaught error was raised while handling the error.') return context = None handled = False sync_modes = [] for group in self.groups: try: for handler in self.handlers[group]: check = handler.check_update(update) if check is not None and check is not False: if not context and self.use_context: context = CallbackContext.from_update(update, self) handled = True sync_modes.append(handler.run_async) handler.handle_update(update, self, check, context) break # Stop processing with any other handler. except DispatcherHandlerStop: self.logger.debug( 'Stopping further handlers due to DispatcherHandlerStop') self.update_persistence(update=update) break # Dispatch any error. except Exception as exc: try: self.dispatch_error(update, exc) except DispatcherHandlerStop: self.logger.debug('Error handler stopped further handlers') break # Errors should not stop the thread. except Exception: self.logger.exception( 'An uncaught error was raised while handling the error.' ) # Update persistence, if handled handled_only_async = all(sync_modes) if handled: # Respect default settings if all(mode is DEFAULT_FALSE for mode in sync_modes) and self.bot.defaults: handled_only_async = self.bot.defaults.run_async # If update was only handled by async handlers, we don't need to update here if not handled_only_async: self.update_persistence(update=update)