我想向主题发送消息,但我在 GitLab issues 和官方文档中没有找到方法。
from datetime import datetime
from telethon import TelegramClient
from telethon.tl.custom import Dialog
from telethon.tl.functions.channels import GetForumTopicsRequest
from telethon.tl.types import PeerChannel, ForumTopic, InputPeerChannel
from telethon.tl.types.messages import ForumTopics
async def main(client: TelegramClient):
async for dialog in client.iter_dialogs(): # type: Dialog
if not dialog.is_group:
continue
print(f"\n{dialog.id=} {dialog.name=}")
if dialog.is_channel and dialog.entity.forum:
input_peer_channel: InputPeerChannel = await client.get_input_entity(PeerChannel(dialog.entity.id))
topics_request = GetForumTopicsRequest(
channel=input_peer_channel, offset_date=datetime.now(), offset_id=-1, offset_topic=-1, limit=50
)
forum_topics: ForumTopics = await client(topics_request)
for topic in forum_topics.topics: # type: ForumTopic
print(f"\t{topic.id=} {topic.title=}")
# QUESTION: How can I send message to the topic?
if __name__ == '__main__':
api_id = 123
api_hash = '123...456'
telegram_client = TelegramClient('user', api_id, api_hash)
with telegram_client:
telegram_client.loop.run_until_complete(main(telegram_client))
向 telegram 子群发送消息的方法
非常感谢@Lomami 的提示,解决了我的问题:
from datetime import datetime
from telethon import TelegramClient
from telethon.tl.custom import Dialog
from telethon.tl.functions.channels import GetForumTopicsRequest, GetForumTopicsByIDRequest
from telethon.tl.types import PeerChannel, ForumTopic, InputPeerChannel, Message
from telethon.tl.types.messages import ForumTopics
async def main(client: TelegramClient):
async for dialog in client.iter_dialogs(): # type: Dialog
if not dialog.is_group:
continue
print(f"\n{dialog.id=} {dialog.name=}")
if dialog.is_channel and dialog.entity.forum:
input_peer_channel: InputPeerChannel = await client.get_input_entity(PeerChannel(dialog.entity.id))
topics_request = GetForumTopicsRequest(
channel=input_peer_channel, offset_date=datetime.now(), offset_id=-1, offset_topic=-1, limit=50
)
forum_topics: ForumTopics = await client(topics_request)
for topic in forum_topics.topics: # type: ForumTopic
print(f"\t{topic.id=} {topic.title=}")
# This block was solved my issue
entity: ForumTopics = await client(GetForumTopicsByIDRequest(channel=dialog.entity, topics=[topic.id]))
channel: InputPeerChannel = await client.get_input_entity(PeerChannel(entity.chats[0].id))
message: Message = await client.send_message(channel, "Hi there!", reply_to=topic.id)
print(message.id)
if __name__ == '__main__':
api_id = 123
api_hash = '123...456'
telegram_client = TelegramClient('user', api_id, api_hash)
with telegram_client:
telegram_client.loop.run_until_complete(main(telegram_client))