def print_problem(bot, updater, *args): time.sleep(random.uniform(0, 0.7)) num = args[0] if 'callback_query' in str(updater): message = updater.callback_query.message else: message = updater.message markup = telegram.ForceReply() players = wr.read_results() if players[str(message.chat.id)][2][len(players[str(message.chat.id)][2]) - 1][2] == 'started': bot.send_message(chat_id=message.chat.id, text=problems[num - 1][0]) if num == 12: bot.send_photo(chat_id=message.chat.id, photo=open('12.jpg', 'rb')) bot.send_message(chat_id=message.chat.id, text='Ваш ответ к задаче {} :'.format(num), reply_markup=markup) else: try: ass = players[str(message.chat.id)][2][len(players[str(message.chat.id)][2]) - 1][1][str(num)] if len(ass) == 1: bot.send_message(chat_id=message.chat.id, text=problems[num - 1][0]) if num == 12: bot.send_photo(chat_id=message.chat.id, photo=open('12.jpg', 'rb')) bot.send_message( chat_id=message.chat.id, text='Ваш ответ к задаче {} :'.format(num), reply_markup=markup) else: bot.send_message( chat_id=message.chat.id, text='Ты уже решил эту задачу)\nИ ответ был {}.'.format( ass[1])) except KeyError: bot.send_message(chat_id=message.chat.id, text='Всё плохо.')
def support(bot, update): """ Sends the support message. Some kind of "How can I help you?". """ bot.send_message(chat_id=update.message.chat_id, text=messages.ASK_FOR_NEW_REQUEST, reply_markup=telegram.ForceReply())
def OnAddIncTyped(bot, update): bot.send_message( chat_id=update.message.chat_id, reply_to_message_id=update.message.message_id, text= "Now, send me your include file. He it should be in format <b>.inc</b>. If he placed in subdir (<b>/include/shop/</b> for example), also send me in caption, where he should be placed.", parse_mode=telegram.ParseMode.HTML, reply_markup=telegram.ForceReply(True))
def state(update: telegram.Update, context: CallbackContext): message = messages.ask_state_msg() chat_id = update.message.chat_id context.bot.send_message( chat_id=chat_id, text=message, parse_mode=telegram.ParseMode.HTML, reply_markup=telegram.ForceReply(), )
def feedback(bot, updater): time.sleep(random.uniform(0, 0.7)) if 'callback_query' in str(updater): id = updater.callback_query.message.chat.id else: id = updater.message.chat.id bot.send_message( chat_id=id, text='Ответив на это сообщение, вы сможете послать нам свой отзыв!', reply_markup=telegram.ForceReply(selective=False))
def flush_db(bot, update): if update.message.chat_id != config.support_chat_id: bot.send_message( chat_id=update.message.chat_id, text=messages.FLUSH_DB_UNAUTHORISED) else: bot.send_message( chat_id=update.message.chat_id, text=messages.FLUSH_DB_ARE_YOU_SURE, reply_markup=telegram.ForceReply())
def askString(self, message, default=None): reply_markup = telegram.ForceReply() message = self.question_tmpl.format(message=message) message = self.bot.sendMessage(chat_id=self.chat_id, text=message, parse_mode="Markdown", reply_markup=reply_markup) self.last_question_id = message.message_id value = self.queue.get() self.last_question_id = None return value
def send_ask_proof(cinfo, chat_id): print('send_ask_proof()') if not cinfo.success: return if cinfo.q2_sent is None: msg_str = 'Great. Would you mind to send me a proof? (send a screenshot from the call log).' data = bot.send_message(chat_id=cinfo.chat_id, text=msg_str, reply_markup=telegram.ForceReply()) print("DATA ++++++++++", data) cinfo.q2_sent_msgid = data["message_id"] cinfo.q2_sent = timezone.now() cinfo.save()
def send_ask_why(cinfo, chat_id): print('send_ask_why()') if cinfo.success: return if cinfo.q2_sent is None: msg_str = 'Oh! Sorry to hear about that. Why the class did not happend? (send one message)' data = bot.send_message(chat_id=cinfo.chat_id, text=msg_str, reply_markup=telegram.ForceReply()) print("DATA ++++++++++", data) cinfo.q2_sent_msgid = data["message_id"] cinfo.q2_sent = timezone.now() cinfo.save()
def send_ask_lenght(cinfo, chat_id): print('send_ask_lenght()') if not cinfo.proof: print('[ ] send_ask_lenght: bool(cinfo.proof) = False') return if cinfo.q3_sent is None: msg_str = 'How long did the class take? (write the number of minutes).' data = bot.send_message(chat_id=cinfo.chat_id, text=msg_str, reply_markup=telegram.ForceReply()) print("DATA ++++++++++", data) cinfo.q3_sent_msgid = data["message_id"] cinfo.q3_sent = timezone.now() cinfo.save()
def main(self, EC): if EC.update.effective_chat.id not in self.enabled_chat_id: return if not EC.update.message: return if EC.update.message.text == '/rmkb': message = EC.update.message.reply_text( text='移除鍵盤中...', quote=True, reply_markup=telegram.ForceReply()) EC.update.message.reply_text( text='已移除鍵盤', quote=True, reply_markup=telegram.ReplyKeyboardRemove()) message.delete()
def change(bot, update): """ Called on callback query fot changes of user data Args: bot (telegram.Bot) - The bot that is running update (telegram.Update) - Incoming Update """ global data chat_id = update.callback_query.message.chat.id if update.callback_query.data == "del": with(open(json_dir + "customers.json")) as file: json_data = json.loads(file.read()) for i in range(0, len(json_data)): if chat_id == json_data[i]["contact"]["chat_id"]: del json_data[i:i + 1] break bot.sendMessage(chat_id, "Deine Account wurde <b>gelöscht</b>", parse_mode="HTML") else: int_id = int(float(update.callback_query.data)) # Adds user to working variables if not there if chat_id not in list(users.keys()): with(open(json_dir + "customers.json")) as file: json_data = json.loads(file.read()) for i in range(0, len(json_data)): if chat_id == json_data[i]["contact"]["chat_id"]: users[chat_id] = json_data[i] break # changes the progress of the registration and send the request for the new value if chat_id not in list(data.keys()): data[chat_id] = {"id": int_id, "edit": True} else: data[chat_id]["id"] = int_id data[chat_id]["edit"] = True bot.sendMessage(chat_id, "Bitte schreib mir nun <b>dein" + names[int_id] + "</b>!", parse_mode="HTML", reply_markup=telegram.ForceReply(True))
def _response_edit(edit_self, edit_update): resp = edit_update.message.text new_config = None try: self._reload_config(content=resp, check_only=True) except Exception as exp: edit_self.send_message( edit_update.message.chat_id, text='Ungültige config: ' + str(exp) + '!\nConfig erneut eingeben. Benutze /cancel zum Abbrechen.', reply_markup=telegram.ForceReply()) return if new_config is not None: self._reload_config(content=resp) edit_self.send_message( edit_update.message.chat_id, text='Erledigt', reply_markup=telegram.ReplyKeyboardRemove()) edit_self.set_handle_response( edit_update.message.chat_id, None)
def input_movie_user(bot, update, possible_original_title, rate=0, info=False): keyboard = [[i] for i in range(len(possible_original_title))] count = 0 if info: for title in possible_original_title: keyboard[count][0] = InlineKeyboardButton(title, callback_data="5 " + title) count += 1 elif rate == 0: for title in possible_original_title: keyboard[count][0] = InlineKeyboardButton(str(title), callback_data="3 " + str(title)) count += 1 else: for title in possible_original_title: keyboard[count][0] = InlineKeyboardButton(title, callback_data="4 " + title + " || " + str(rate)) count += 1 try: reply_markup = InlineKeyboardMarkup(keyboard) update.message.reply_text('Which one?', reply_markup=reply_markup) except: chat_id = update.message.chat_id bot.send_message(chat_id=chat_id, text="Invalid name \n[Too short/long, or does't exist]") bot.send_message(chat_id, 'Insert the name of the movie', reply_markup=telegram.ForceReply(force_reply=True)) flag_input_start = True
def start(bot, update): """ /start starts the register process Args: bot (telegram.Bot) - The bot that is running update (telegram.Update) - Incoming Update """ global data, users chat_id = int(float(update.message.chat_id)) if registered(chat_id): bot.sendMessage(chat_id, "<b>Du bist schon registriert</b>", parse_mode="HTML") else: # Variable to check how far the register process is and weather it is a change of data or the register data[chat_id] = {"id": 0, "edit": False} if chat_id not in list(users.keys()): # Variable where the user json format is initialised # Generates an unique id and saves the chat ID users[chat_id] = {"id": get_new_id(), "firstname": "", "lastname": "", "email": None, "password": None, "contact": {"name": None, "postcode": None, "street": None, "city": None, "nr": None, "phone": None, "chat_id": chat_id}} bot.sendMessage(chat_id, "Geben Sie bitte Ihren <b>Vornamen</b> ein", parse_mode="HTML", reply_markup=telegram.ForceReply(True))
def verifypic(bot, update): reply_markup = telegram.ForceReply(force_reply=True) bot.sendMessage(update.message.chat_id, text="Please attach your picture as a reply to this message, and I will " + "attempt to send it to the admins.",reply_markup=reply_markup)
def comandos(bot, update): chat_id = update.message.chat_id #id del chat respuesta = update.message.reply_to_message #mensaje de respuesta global mail #variable global de mail global contra #variable global de contraseña if (respuesta.text == "Cuenta:"): #Receptor de la cuenta a usar Email_Regex = re.compile(r"^[A-Za-z0-9\.\+_-]+@[gmail]+\.[com]*$" ) #Expresión regular del mensaje de respuesta mail = update.message.text #Texto del mensaje if ( not Email_Regex.match(mail) ): #if de condicion para validar que el correo cumpla con la expresión regular bot.send_message( chat_id=chat_id, text="No tiene la estructura correcta ([email protected])" ) #mensaje de error bot.send_message(chat_id=chat_id, text="Cuenta:", reply_markup=telegram.ForceReply( True)) #mensaje de cuenta nuevo else: bot.send_message(chat_id=chat_id, text="Contraseña:", reply_markup=telegram.ForceReply(True)) elif (respuesta.text == "Contraseña:"): #Handler contraseña contra = update.message.text #texto de la contraseña if (not (mail is None) and not (contra is None)): #valida que ambas tengan valores with IMAPClient(HOST) as server: try: #Primera conexion para verificar los datos server.login(mail, contra) bot.send_sticker(chat_id=update.message.chat_id, sticker='CAADAgADsggAAgi3GQITL8y1531UoQI' ) # Sticker deberia ir aqui #menu de opciones una vez conectado keyboard = [[ InlineKeyboardButton("Revisar", callback_data="revisar"), InlineKeyboardButton("Enviar", callback_data="enviar") ]] reply_markup = InlineKeyboardMarkup(keyboard, one_time_keyboard=True) bot.send_message(chat_id=chat_id, text="¿Qué quieres hacer?", reply_markup=reply_markup) except: #mensaje de error bot.send_sticker(chat_id=chat_id, sticker='CAADAgADvQgAAgi3GQJ5Y2qUgnnOKgI' ) #Sticker deberia ir aqui keyboard = [[ InlineKeyboardButton("Si", callback_data="conection"), InlineKeyboardButton("No", callback_data="conectioff") ]] reply_markup = InlineKeyboardMarkup(keyboard, one_time_keyboard=True) bot.send_message(chat_id=chat_id, text="¿Quieres intentar nuevamente?", reply_markup=reply_markup) elif (respuesta.text == "Destino:"): #Mensaje para la cuenta destino Email_Regex = re.compile( r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$" ) #Expresion regular para la cuenta a enviar mailes = update.message.text #mails a enviar correos = mailes.split( ', ') #en caso de varias cuentas esto es necesario validador = False #variable de posible uso de los mails for correo in correos: #for para los correos de destinos y verificar su estructura if (not Email_Regex.match(correo)): bot.send_message( chat_id=chat_id, text="No tiene la estructura correcta ([email protected])") bot.send_message(chat_id=chat_id, text="Destino:", reply_markup=telegram.ForceReply(True)) validador = False break else: validador = True if (validador): aenviar["To"] = mailes #carga del destino bot.send_message( chat_id=chat_id, text="Asunto:", reply_markup=telegram.ForceReply(True)) #envia el proximo paso #manejador paso del asunto elif (respuesta.text == "Asunto:"): aenviar[ "Subject"] = update.message.text #carga del asunto del mensaje (temporal hasta agregar archivos adjuntos) bot.send_message(chat_id=chat_id, text="Mensaje:", reply_markup=telegram.ForceReply( True)) #mensaje para el cuerpo del correo elif (respuesta.text == "Mensaje:" ): #manejador del cuerpo y el envio del mensaje aenviar.attach(MIMEText(update.message.text, "plain")) #agrega el mensaje keyboard = [[ InlineKeyboardButton("Si", callback_data="adjuntar"), InlineKeyboardButton("No", callback_data="noadjuntar") ]] reply_markup = InlineKeyboardMarkup(keyboard, one_time_keyboard=True) bot.send_message(chat_id=chat_id, text="¿Desea adjuntar algún archivo?", reply_markup=reply_markup)
def button(bot, update): query = update.callback_query chat_id = query.message.chat_id option = str(query.data.split(' ')[0]) # START if option == "1": title = ' '.join(query.data.split(' ')[1:]).lower() user_name = str(update['callback_query']['from_user']['username']) if len(user_name) < 5: bot.send_message(chat_id=chat_id, text="\t-- !ERROR! --\nYour data won't be save\nYou don't have a username set on Telegram"\ "[How to do it](https://telegram.org/blog/usernames-and-secret-chats-v2)") original_title = search(title, partial=False) if original_title: bot.edit_message_text(text=f"Selected option: {original_title}", chat_id=chat_id, message_id=query.message.message_id) add_rating(user_name, original_title, 5) # bot.send_message(chat_id=chat_id, text="Wait for the recommandation") # RECOMMANDATION recommended_movies = movies_from_last_one(str(user_name)) keyboard = [[i] for i in range(len(recommended_movies))] count = 0 for title, value in recommended_movies: keyboard[count][0] = InlineKeyboardButton(str(title), callback_data="3 " + str(title)) count += 1 reply_markup = InlineKeyboardMarkup(keyboard) bot.send_message(chat_id=chat_id, text='Click your favorite movie', reply_markup=reply_markup) else: bot.edit_message_text(chat_id=chat_id, text="Invalid name \n[Too short/long, or does't exist]", message_id=query.message.message_id) # INPUT USER elif option == "2": global flag_input_start bot.send_message(chat_id, 'Insert the name of the movie', reply_markup=telegram.ForceReply(force_reply=True)) flag_input_start = True # SHOW MOVIE AND RATING elif option == "3": title = ' '.join(query.data.split(' ')[1:]) user_name = str(update['callback_query']['from_user']['username']) bot.edit_message_text(text=f"Selected option: {title}", chat_id=chat_id, message_id=query.message.message_id) keyboard = [ [ InlineKeyboardButton("1", callback_data="4 " + title + " || 1"), InlineKeyboardButton("2", callback_data="4 " + title + " || 2"), InlineKeyboardButton("3", callback_data="4 " + title + " || 3") ], [ InlineKeyboardButton("4", callback_data="4 " + title + " || 4"), InlineKeyboardButton("5", callback_data="4 " + title + " || 5") ] ] reply_markup = InlineKeyboardMarkup(keyboard) bot.send_message(chat_id=chat_id, text='Insert your personal rating for the movie', reply_markup=reply_markup) # SAVE AND ASK AGAIN elif option == "4": option2 = ' '.join(query.data.split(' ')[1:]) user_name = str(update['callback_query']['from_user']['username']) title, rating = option2.split(' || ') bot.edit_message_text(text=f"{int(rating)}/5 for {title}", chat_id=chat_id, message_id=query.message.message_id) add_rating(user_name, title, int(rating)) # bot.send_message(chat_id=chat_id, text="Wait for the recommandation") recommended_movies = movies_from_last_one(str(user_name)) keyboard = [[i] for i in range(len(recommended_movies))] count = 0 for title, value in recommended_movies: keyboard[count][0] = InlineKeyboardButton(str(title), callback_data="3 " + str(title)) count += 1 reply_markup = InlineKeyboardMarkup(keyboard) bot.send_message(chat_id=chat_id, text='Click your favorite movie', reply_markup=reply_markup) # INFO MOVIE elif option == "5": user_name = str(update['callback_query']['from_user']['username']) title = ' '.join(query.data.split(' ')[1:]) md = get_md() row_title = md.loc[md['title'] == title] # adult,belongs_to_collection,budget,genres,homepage,id, # imdb_id,original_language,original_title,overview,popularity, # poster_path,production_companies,production_countries,release_date, # revenue,runtime,spoken_languages,status,tagline,title,video,vote_average,vote_count message = "*" + str(row_title['original_title'].values[0]).upper() + "* \n" + \ "*Release Date*: " + str(row_title['release_date'].values[0]) + "\n" # "*Genres*: " + ','.join([row_title['genres'].values[i] for i in range(len(row_title['genres']))]) + "\n" + \ # "*Runtime*: " + str(row_title['runtime'].values[0]) + " minuts\n" + \ # "*Overview*:\n" + str(row_title['overview'].values[0]) # "[How to do it](https://telegram.org/blog/usernames-and-secret-chats-v2)" bot.edit_message_text(chat_id=chat_id, text=message, message_id=query.message.message_id, parse_mode=telegram.ParseMode.MARKDOWN) bot.send_photo(chat_id=chat_id, photo="https://image.tmdb.org/t/p/original/" + str(row_title['poster_path'].values[0]))
def answer_problem(bot, updater): time.sleep(random.uniform(0, 0.7)) message = updater.message players = wr.read_results() try: if players[str(message.from_user.id)][2][len( players[str(message.from_user.id)][2]) - 1][3] == 'ended': bot.send_message(chat_id=message.chat.id, text='Уже всё(') else: res = players[str(message.from_user.id)][2][len( players[str(message.from_user.id)][2]) - 1][1] markup = telegram.ReplyKeyboardRemove(selective=False) ans = message.text rep = message.reply_to_message.text num = int(rep[19:-2]) try: a = float(ans) if len(res[str(num)]) == 2: bot.send_message( chat_id=message.chat.id, text='Ты уже ответил на этот вопрос!') else: if players[str(message.chat.id)][2][len(players[str(message.chat.id)][2]) - 1][3] == 'started': res[str(num)].append(ans) if ans == problems[num-1][1]: bot.send_message(chat_id=message.chat.id, text='Ответ верный!') else: bot.send_message(chat_id=message.chat.id, text='Ответ неверный!') if num == len(problems): players[str(message.from_user.id)][2][len( players[str(message.from_user.id)][2]) - 1][3] = "ended" wr.write_results(players) bot.send_message( chat_id=message.chat.id, text='Ура! Тур завершён!\nРезультаты будут опубликованы в группе:\nvk.com/economic_carousel') result(bot, updater) bot.send_message( chat_id=message.chat.id, text='А сейчас вы сможете оставить свой комментарий/пожелания, например, какая задача вам понравилась больше всего, какая меньше.\nhttps://goo.gl/forms/XBIyXoYEEQUrB9IB2\nСпасибо большое, за то что приняли участие в проекты, если вы хотите поддержать нас, то ') donate(bot, updater) select_problems(bot, updater) else: wr.write_results(players) print_problem(bot, updater, num + 1) else: if problems[num - 1][1] == ans: if len(res[str(num)]) == 1: res[str(num)].append(ans) else: res[str(num)][1] = ans wr.write_results(players) bot.send_message( chat_id=message.chat.id, text="Верно!", reply_markup=markup) else: bot.send_message( chat_id=message.chat.id, text="Неправильно(\nПопробуй еще!", reply_markup=markup) markup = telegram.ForceReply(selective=False) bot.send_message( chat_id=message.chat.id, text='Ваш ответ к задаче {} :'.format(num), reply_markup=markup) except ValueError: bot.send_message( chat_id=message.chat.id, text="Неправильный формат ответа!\nПопробуй еще!", reply_markup=markup) markup = telegram.ForceReply(selective=False) bot.send_message( chat_id=message.chat.id, text='Ваш ответ к задаче {} :'.format(num), reply_markup=markup) except KeyError: bot.send_message(chat_id=message.chat.id, text='Ты ещё не начал.')
def button(bot, update): #Función de manejo de botones query = update.callback_query #variable para almacenar el mensaje de llamada a los botones if ( query.data == "conectioff" ): #Mensaje de conexion en caso de no querer usar los servicios o desconexión bot.edit_message_text( chat_id=query.message.chat_id, message_id=query.message.message_id, text="Gracias por usar nuestro bot." ) #editor del mensaje del boton para que no se presione más de una vez elif (query.data == "conection"): #Mensaje de conexion positiva bot.edit_message_text( chat_id=query.message.chat_id, message_id=query.message.message_id, text= "Para conectarse es necesario que nos indique su cuenta y contraseña" ) #editor del mensaje del boton para que no se presione más de una vez #envio de mensaje con forcereply, para obligar al usuario a responder al mensaje de manera que se realice un formulario bot.send_message(chat_id=query.message.chat_id, text="Cuenta:", reply_markup=telegram.ForceReply(True)) elif (query.data == "revisar"): #Opcion de revisar mensaje bot.edit_message_text( chat_id=query.message.chat_id, message_id=query.message.message_id, text="Veamos tus mensajes nuevos") #Editor de mensaje with IMAPClient( HOST ) as server: #Realiza la conexion de nuevo, proceso IMAP del laboratorio 1 server.login( mail, contra ) #Login con el mail y la contraseña ingresada por el usuario server.select_folder('INBOX', readonly=False) #Selecciona la carpeta texto = '' #Variable para manejar el while while (texto == ''): #While para manejar la recepción de mensajes try: server.idle() #Conexion Idle responses = server.idle_check(timeout=1) #Verificación server.idle_done() recibido = server.search( 'UNSEEN') #Recibe los mensaje no vistos if (not (recibido == [])): #verifica que haya mensajes nuevos bot.send_message( chat_id=query.message.chat_id, text="Mensajes nuevos:") #mensaje de apertura for uid, message_data in server.fetch( recibido, 'RFC822').items(): #for de impresion email_message = email.message_from_bytes( message_data[b'RFC822']) texto = "De:\n" + email_message.get( 'From') + "\nAsunto:\n" + email_message.get( 'Subject') bot.send_message(chat_id=query.message.chat_id, text=texto) #Envio de mensaje if not SET_READ: server.remove_flags(recibido, [SEEN]) else: bot.send_message(chat_id=query.message.chat_id, text="No hay nuevos mensajes") texto = "1" except KeyboardInterrupt: server.logout() exit() #Generación del teclado para verificar si se quiere hacer algo mas rep(bot, query.message.chat_id) #opción de enviar mensaje elif (query.data == "enviar"): global aenviar #variable global de creacion de el objeto mensaje aenviar = MIMEMultipart() bot.edit_message_text( chat_id=query.message.chat_id, message_id=query.message.message_id, text= "Para enviar un mensaje es necesario que nos proporcione cierta información." ) bot.send_message( chat_id=query.message.chat_id, text= "En el caso de haber varios destinatarios separelos con una coma y un espacio (', ') unicamente" ) #respuesta obligatoria para el destino del mensaje, luego de la explicación para enviar el mensaje a varios destinatarios bot.send_message(chat_id=query.message.chat_id, text="Destino:", reply_markup=telegram.ForceReply(True)) elif (query.data == "adjuntar"): bot.edit_message_text(chat_id=query.message.chat_id, message_id=query.message.message_id, text="Envienos el archivo a continuación") bot.send_message(chat_id=query.message.chat_id, text="Archivo:", reply_markup=telegram.ForceReply(True)) elif (query.data == "noadjuntar"): bot.edit_message_text( chat_id=query.message.chat_id, message_id=query.message.message_id, text="Todo listo, procederemos a enviar el correo") envio(bot, query.message.chat_id) #repeticion final rep(bot, query.message.chat_id)
def textConvert(bot, update): bot.send_message(update.message.chat_id, c.TEXT_CONVERT_TEXT, reply_to_message_id=update.message.message_id, reply_markup=telegram.ForceReply()) return STYLE_CATEGORY_SELECT
def reply(bot, update): """ Is called, when somebody reply to an message Checks the value that should be inserted or changed Args: bot (telegram.Bot) - The bot that is running update (telegram.Update) - Incoming Update """ global data, users chat_id = update.message.chat_id # if user is at this point # saves the input to variable # if it is not an change # the next question is asked # register progress is changed # Vorname if data[chat_id]["id"] == 0: users[chat_id]["firstname"] = update.message.text if not data[chat_id]["edit"]: bot.sendMessage(chat_id, "Bitte geben Sie Ihren <b>Nachnamen</b> ein", parse_mode="HTML", reply_markup=telegram.ForceReply(True)) data[chat_id]["id"] = 1 # Nachname elif data[chat_id]["id"] == 1: users[chat_id]["lastname"] = update.message.text if not data[chat_id]["edit"]: bot.sendMessage(chat_id, "Was ist Ihre <b>E-Mail Adresse</b>?", parse_mode="HTML", reply_markup=telegram.ForceReply(True)) data[chat_id]["id"] = 2 # Email elif data[chat_id]["id"] == 2: users[chat_id]["email"] = update.message.text if not data[chat_id]["edit"]: bot.sendMessage(chat_id, "Vergeben Sie bitte ein sicheres <b>Passwort</b>", parse_mode="HTML", reply_markup=telegram.ForceReply(True)) data[chat_id]["id"] = 3 # Password elif data[chat_id]["id"] == 3: users[chat_id]["password"] = update.message.text if not data[chat_id]["edit"]: bot.sendMessage(chat_id, "In welcher <b>Stadt</b> haben Sie Ihren Wohnsitz?", parse_mode="HTML", reply_markup=telegram.ForceReply(True)) data[chat_id]["id"] = 4 # Stadt elif data[chat_id]["id"] == 4: users[chat_id]["contact"]["city"] = update.message.text if not data[chat_id]["edit"]: bot.sendMessage(chat_id, "Wie lautet die <b>Postleitzahl</b> Ihres Wohnortes?", parse_mode="HTML", reply_markup=telegram.ForceReply(True)) data[chat_id]["id"] = 5 # PLZ elif data[chat_id]["id"] == 5: users[chat_id]["contact"]["postcode"] = int(float(update.message.text)) if not data[chat_id]["edit"]: bot.sendMessage(chat_id, "In welcher <b>Straße</b> wohnen Sie? (<b>ohne</b> Hausnummer)", parse_mode="HTML", reply_markup=telegram.ForceReply(True)) data[chat_id]["id"] = 6 # Strasse elif data[chat_id]["id"] == 6: users[chat_id]["contact"]["street"] = update.message.text if not data[chat_id]["edit"]: bot.sendMessage(chat_id, "Was ist ihre <b>Hausnummer</b>?", parse_mode="HTML", reply_markup=telegram.ForceReply(True)) data[chat_id]["id"] = 7 # Nr elif data[chat_id]["id"] == 7: users[chat_id]["contact"]["nr"] = update.message.text if not data[chat_id]["edit"]: bot.sendMessage(chat_id, "Unter welcher <b>Nummer</b> sind Sie erreichbar?", parse_mode="HTML", reply_markup=telegram.ForceReply(True)) data[chat_id]["id"] = 8 # Phone elif data[chat_id]["id"] == 8: users[chat_id]["contact"]["phone"] = update.message.text if not data[chat_id]["edit"]: bot.sendMessage(chat_id, "<b>Danke!</b>", parse_mode="HTML") data[chat_id]["id"] = 9 # Auto generates the name, from first ans last name users[chat_id]["contact"]["name"] = users[chat_id]["firstname"] + " " + users[chat_id]["lastname"] data[chat_id]["edit"] = False # Saves the progress/changes to the "customers.json" with open(json_dir + "customers.json", "r") as f: json_data = json.load(f) found = False for i in range(0, len(json_data)): if chat_id == json_data[i]["contact"]["chat_id"]: json_data[i] = users[chat_id] found = True break if not found: json_data.append(users[chat_id]) with open(json_dir + "customers.json", "w") as f: f.write(json.dumps(json_data))
def hmp(bot, updater): bot.send_message(chat_id=updater.message.chat.id, text='Reply to this message with photos', reply_markup=telegram.ForceReply()) time.sleep(4) btnlist = [ telegram.InlineKeyboardButton('Photos.', callback_data='photos'), telegram.InlineKeyboardButton('Files.', callback_data='files'), ] markup = telegram.InlineKeyboardMarkup(cropper.build_menu(btnlist, n_cols=2)) bot.send_message(chat_id=updater.message.chat.id, text='What type of output do you prefer?', reply_markup=markup)
def _response(resp_self, resp_update): if resp_update.message.text == 'Inhalt': with open(resp_self.config_file) as fp: config_text = fp.read() resp_self.send_message( resp_update.message.chat_id, text=config_text, reply_markup=telegram.ReplyKeyboardRemove()) resp_self.set_handle_response(resp_update.message.chat_id, None) elif resp_update.message.text == 'Neuladen': self._reload_config() resp_self.send_message( resp_update.message.chat_id, text='Erledigt', reply_markup=telegram.ReplyKeyboardRemove()) resp_self.set_handle_response(resp_update.message.chat_id, None) elif resp_update.message.text == 'Bearbeiten': resp_self.send_message( resp_update.message.chat_id, text= 'Inhalt der Config Datei eingeben!\nBenutze /cancel zum Abbrechen.', reply_markup=telegram.ForceReply()) def _response_edit(edit_self, edit_update): resp = edit_update.message.text new_config = None try: self._reload_config(content=resp, check_only=True) except Exception as exp: edit_self.send_message( edit_update.message.chat_id, text='Ungültige config: ' + str(exp) + '!\nConfig erneut eingeben. Benutze /cancel zum Abbrechen.', reply_markup=telegram.ForceReply()) return if new_config is not None: self._reload_config(content=resp) edit_self.send_message( edit_update.message.chat_id, text='Erledigt', reply_markup=telegram.ReplyKeyboardRemove()) edit_self.set_handle_response( edit_update.message.chat_id, None) resp_self.set_handle_response(resp_update.message.chat_id, _response_edit) elif resp_update.message.text == 'Abbrechen': resp_self.cmd_cancel(bot, resp_update) else: resp_self.send_message( resp_update.message.chat_id, text='Bitte wähle eine der folgenden Möglichkeiten', reply_markup=self._reply_config)