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

Telethon调用send_message()返回Message遍历报不可迭代错误

错误原因

client.send_message() 单次调用的返回值是单个Message对象实例,并非包含多条消息的可迭代列表。直接对单个非可迭代对象执行for遍历,就会触发TypeError: 'Message' object is not iterable报错。

修复实现

你不需要写循环遍历,单条消息的属性可以直接从返回的s对象上读取:

s = client.send_message(entity='group', message='Thank you!', reply_to=chatid)

# 直接读取单条消息的对应属性
new_msg_id = s.id
new_msg_content = s.message
new_sender_id = s.from_id

# 如果需要存入列表,直接追加即可,无需循环
message_id = []
message = []
sender = []
message_id.append(new_msg_id)
message.append(new_msg_content)
sender.append(new_sender_id)

获取目标chatid

返回的Message对象的peer_id属性存储了当前消息所属对话的ID信息,根据对话类型取值即可:

  • 群组/频道场景:peer_id为PeerChannel类型,取s.peer_id.channel_id就是群组ID
  • 私聊场景:peer_id为PeerUser类型,取s.peer_id.user_id就是对端用户ID

提取群组chatid的参考代码:

from telethon.tl.types import PeerChannel

if isinstance(s.peer_id, PeerChannel):
    group_chatid = s.peer_id.channel_id
    print(f"当前群组ID:{group_chatid}")

注意:只有调用批量获取/批量发送消息的方法(如get_messages()拉取多条历史消息),返回值是Message对象列表时,才需要使用for循环遍历逐个读取属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 12:06:17