import telebot import re TOKEN = '' bot = telebot.TeleBot(TOKEN) receiveReference = False reference = '' pattern = "http[s]?:\/\/(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+" refPattern = "ref=.*\?" @bot.message_handler(commands=['start']) def send_welcome(message): bot.reply_to(message, "Hello, I'm ready.") @bot.message_handler(commands=['help']) def send_help(message): bot.reply_to(message, "My commands are: /start, /help, /reference") @bot.message_handler(commands=['reference']) def send_question(message): global receiveReference receiveReference = True bot.reply_to(message, "Tell me, what's your reference code?.") @bot.message_handler() def process_response(message): global receiveReference, reference if(len(reference) > 0): result = re.match(pattern, message.text) if(result): url = result.group() print("[INFO] Found URL match on: %s" % url) refResult = re.search(refPattern, url) if(refResult): ref = refResult.group() print("[INFO] Found reference match on: %s" % ref) newMessage = message.text.replace(ref, "ref=%s?" % reference) bot.send_message(message.chat.id, newMessage) bot.delete_message(chat_id=message.chat.id, message_id=message.message_id) else: print("[INFO] No reference pattern matched") else: print("[INFO] No URL pattern matched") elif(receiveReference): reference = message.text bot.reply_to(message, "OK, your reference is: %s, send me now any URL." % reference) receiveReference = False else: print("[INFO] Receive reference disabled, try /reference") try: print('[INFO] Bot started...') bot.polling() except Exception as ex: print("Something goes wrong, exception: ", ex)