Search code examples
pythontelegram

Line break when sending the command telegram py


I have this code, I defined the # as a separator between the trigger and the answer (repeat).

But, I try to make a line space and the bot doesn't consider it as such.

For example: I am writing:

/addfilter trigger # hey
hey
hey

When I send 'trigger', the bot sends hey hey hey (in the same line, instead of separate lines):

filters_file = "filters.json"
filters = {}

def load_filters():
    global filters
    if os.path.isfile(filters_file):
        with open(filters_file, 'r') as file:
            filters = json.load(file)
    else:
        filters = {} 

def save_filters():
    with open(filters_file, 'w') as file:
        json.dump(filters, file, indent=4)

def add_filter(update: Update, context: CallbackContext):
    load_filters()
    chat_id = update.effective_chat.id

    if not update.effective_chat.type == 'supergroup':

        return

    user_id = update.effective_user.id
    existing_filters_count = len(filters.get(str(chat_id), {}))
    max_filters = 30  # Maximum number of filters allowed

    if existing_filters_count >= max_filters:
        return

    if not context.args or len(context.args) < 2:
        return
    input_args = " ".join(context.args).split('#', 1)

    if len(input_args) != 2:
      return

    trigger = input_args[0].strip()
    reply = input_args[1].strip() 
    reply = reply.replace('#', '')

    if str(chat_id) not in filters:
        filters[str(chat_id)] = {}

    if trigger in filters[str(chat_id)]:

        return

    filters[str(chat_id)][trigger] = reply
    save_filters()

    context.bot.send_message(chat_id=chat_id, text="✅", reply_to_message_id=update.message.message_id)



def check_filter(update: Update, context: CallbackContext):
    load_filters()

    chat_id = update.effective_chat.id
    text = update.message.text

    if str(chat_id) in filters:
        for trigger, reply in filters[str(chat_id)].items():
            if trigger.lower() == text.lower():
                context.bot.send_message(chat_id=chat_id, text=reply, parse_mode=ParseMode.HTML, reply_to_message_id=update.message.message_id)
                break

Solution

  • context.args is the result of splitting the message’s text on single or consecutive whitespaces.[1]

    You have to extract the content yourself from the message’s text. Here’s how you can do that:

    reply = update.effective_message.text.split(None, 2)[2].replace("#", "", 1)