You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Telegram机器人过滤器回复换行失效问题求助

问题原因

你遇到的换行丢失问题,根源在add_filter函数里的这行代码:

input_args = " ".join(context.args).split('#', 1)

Telegram Bot的context.args会把用户发送的消息按**所有空白字符(包括换行、空格)**拆分成列表,再用" ".join拼接时,所有换行都会被替换成空格,存到JSON里的回复内容自然丢失了换行,触发时也就不会显示换行。

解决方法

直接从update.message.text中提取完整内容,跳过context.args的处理,这样就能保留换行:

修改add_filter函数里的输入处理部分,替换原来的context.args相关逻辑:

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

    # 直接获取完整消息文本,去掉开头的命令部分
    full_text = update.message.text.strip()
    if not full_text.startswith('/addfilter'):
        return
    
    # 去掉命令前缀,分割触发词和回复内容
    content = full_text[len('/addfilter'):].strip()
    input_args = content.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)
关键说明
  • 用update.message.text直接获取用户发送的完整消息,包含换行符。
  • 去掉/addfilter命令前缀后,用split('#', 1)分割,回复内容里的换行、#都会被完整保留。
  • 原代码的reply.replace('#', '')如果不是必须移除回复里的#,可以注释掉,避免误删回复内容中的#。

修改后,当你发送:

/addfilter trigger # hey
hey
hey

机器人保存的回复内容会保留换行,触发时就会显示成:

hey
hey
hey

内容的提问来源于stack exchange,提问作者Post

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 17:05:30