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

Telethon监听Telegram消息时if语句异常触发问题求助

问题

我用Telethon监听Telegram频道新消息,消息接收正常,但加了判断消息是否包含特定文本的if语句后,哪怕消息不含该文本,语句也每次触发。我是新手,找不到问题出在哪,求指点。

附上代码:

from telethon import TelegramClient, events, sync

@client.on(events.NewMessage(chats=chat_id))
async def newMessageListener(event):
    new_message = event.message.message
    chat_id = event.chat_id
    print(chat_id)
    print(new_message)
    
    if "rain" in new_message:
          do_stuff

with client:
    client.run_until_disconnected()

dir(new_message)的结果:

[
     '__add__',
     '__class__',
     '__contains__',
     '__delattr__',
     '__dir__',
     '__doc__',
     '__eq__',
     '__format__',
     '__ge__',
     '__getattribute__',
     '__getitem__',
     '__getnewargs__',
     '__gt__',
     '__hash__',
     '__init__',
     '__init_subclass__',
     '__iter__',
     '__le__',
     '__len__',
     '__lt__',
     '__mod__',
     '__mul__',
     '__ne__',
     '__new__',
     '__reduce__',
     '__reduce_ex__',
     '__repr__',
     '__rmod__',
     '__rmul__',
     '__setattr__',
     '__sizeof__',
     '__str__',
     '__subclasshook__',
     'capitalize',
     'casefold',
     'center',
     'count',
     'encode',
     'endswith',
     'expandtabs',
     'find',
     'format',
     'format_map',
     'index',
     'isalnum',
     'isalpha',
     'isascii',
     'isdecimal',
     'isdigit',
     'isidentifier',
     'islower',
     'isnumeric',
     'isprintable',
     'isspace',
     'istitle',
     'isupper',
     'join',
     'ljust',
     'lower',
     'lstrip',
     'maketrans',
     'partition',
     'replace',
     'rfind',
     'rindex',
     'rjust',
     'rpartition',
     'rsplit',
     'rstrip',
     'split',
     'splitlines',
     'startswith',
     'strip',
     'swapcase',
     'title',
     'translate',
     'upper',
     'zfill'
]

问题排查与解决

从dir(new_message)结果来看,new_message是标准Python字符串,"rain" in new_message语法本身没问题,大概率是以下细节没注意到:

1. 先确认do_stuff是否真被触发

别凭感觉判断,把do_stuff换成明确的调试输出:

if "rain" in new_message:
    print("===== 检测到rain,执行逻辑 =====")
    do_stuff
else:
    print("===== 未检测到rain =====")

看控制台输出就能明确:是判断逻辑出错,还是do_stuff在其他地方被调用了。

2. 检查消息中的隐藏字符或大小写

  • 用print(repr(new_message))代替普通print,能显示所有隐藏特殊字符(比如空格、换行、Unicode特殊字母),避免看起来是"rain"但实际是其他字符的情况。
  • 如果需要忽略大小写匹配,改成if "rain" in new_message.lower()。

3. 试试Telethon自带的过滤功能

Telethon的events.NewMessage支持直接通过pattern参数过滤消息,不用自己写if判断,更可靠高效:

@client.on(events.NewMessage(chats=chat_id, pattern=r'rain'))  # 正则匹配,默认区分大小写
async def newMessageListener(event):
    new_message = event.message.message
    chat_id = event.chat_id
    print(chat_id)
    print(new_message)
    do_stuff

要忽略大小写的话,加标志位:pattern=r'rain', flags=re.IGNORECASE(记得先导入re模块)。

4. 排除变量冲突或空消息

  • 函数内的chat_id = event.chat_id和装饰器里的全局chat_id重名,虽不影响if判断,但建议改名(比如current_chat_id)避免混淆。
  • 确认new_message不是空字符串,空串不可能包含"rain",如果空消息还触发,检查是不是把判断写反成not in了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 15:35:21