python - 使用 Telethon 将消息转发到超级组
问题描述
最近我编写了代码,应该将来自某个用户的每条消息转发到我加入的所有组,但事实并非如此。这是我的代码:
for message in client.iter_messages('aliakhtari78'):
try:
dialogs = client.get_dialogs()
for dialog in dialogs:
id_chat = dialog.message.to_id.channel_id
entity = client.get_entity(id_chat)
client.forward_messages(
entity, # to which entity you are forwarding the messages
message.id, # the IDs of the messages (or message) to forward
'somebody' # who sent the messages?
)
except:
pass
在这段代码中,我首先获取“aliakhtari78”发送给我的每条消息,然后获取我加入的组的实体,最后它应该将消息转发给所有组,但它没有,我检查了我的代码并用用户实体替换实体并且它有效,我知道问题是因为实体,但我无法找出我的问题。 另外,我很抱歉在我的问题中写错了。
解决方案
为了向 Telegram 中的任何实体发送消息,您需要两条信息:
- 实体的常量唯一 ID(它是一个整数。它不是用户名字符串)
- 每个实体的
access_hash
每个用户都不同
您只能传递@username
到client.get_entity
,并且 Telethon 会自动将 解析@username
为具有id
和的实体access_hash
。这就是为什么当您像这样更改代码时它会起作用的原因。但是,在您的代码中,您已将channel_id
(实体的常量唯一 ID)传递给client.get_entity
,而不是username
。
请注意,与 一起client.get_dialogs
返回。您刚刚忽略了实体!这是获取所有实体数组的方法:entities
dialogs
dialogs, entities = client.get_dialogs()
entities
然后只需将数组中的相应实体传递给client.forward_messages
.
推荐阅读
- python - 如何通过添加一个月来操作索引列?
- c# - 在 ms 图表 - winform 中,我希望 RangeBar 图表以 x 轴为中心
- html - 容器元素上的背景图像不显示容器的所有部分
- powershell - 用于用新名称替换文档库中的多个 PDF 文件的 Powershell 脚本
- ios - 如何构建独立应用程序对真实设备的本机博览会做出反应?
- python - 如何使用正则表达式删除特定单词之间特定位置的空格?
- android-studio - 如何让用户复制文本并获得通知?
- php - 在 PHP 中验证请求
- php - Laravel Eager Loading 与分区表
- python - 二阶 ODE 系统 Runge Kutta 四阶