美好的一天,
我目前正在开发一个项目,我需要使用 Telegram 机器人创建一个主题,然后在该主题中发布消息。我的挑战是弄清楚如何在创建主题后立即检索主题 ID(在主题上下文中称为 message_thread_id)。此 ID 对于我的下一步至关重要,其中涉及通过机器人向主题发送消息。但是,如果事先不知道主题 ID,我将无法继续发布消息。谁能指导我如何在代码中创建主题 ID 后立即获取主题 ID,以便我可以将其用于消息传递目的?
我希望通过实现以下功能来增强与 Telegram 群组交互的脚本: 脚本应首先验证群组中是否已存在特定主题名称。如果该主题存在,脚本将使用机器人向该主题发送消息。但是,如果主题不存在,脚本应该能够创建新主题,然后继续向其发送消息。此过程旨在自动将消息发布到组内现有的和新创建的主题。
最诚挚的问候,安德烈
美好的一天, 机器人可以使用这种方法: channels.createForumTopic
代码是:
from telethon import TelegramClient
from telethon.tl.functions.channels import GetFullChannelRequest, CreateForumTopicRequest
from telethon.tl.types import InputChannel, MessageActionTopicCreate
import asyncio
api_id =
api_hash =
async def fetch_channel_info(client, channel_username):
channel = await client.get_entity(channel_username)
full_channel = await client(GetFullChannelRequest(channel))
# The channel object contains the id and access_hash
return channel.id, channel.access_hash
async def create_forum_topic(client, channel_username, topic_name):
channel_id, access_hash = await fetch_channel_info(client, channel_username)
input_channel = InputChannel(channel_id, access_hash)
result = await client(CreateForumTopicRequest(
channel=input_channel,
title=topic_name,
# Add other parameters as needed
))
created_topic_id = None
created_topic_title = None
# Iterate through the updates to find the UpdateNewChannelMessage with the forum topic creation action
for update in result.updates:
if hasattr(update, "message") and hasattr(update.message, "action") and isinstance(update.message.action,
MessageActionTopicCreate):
created_topic_id = update.message.id
created_topic_title = update.message.action.title
break # Assuming you only create one topic per request and can exit the loop once found
# Check if we found the topic creation update and print the information
if created_topic_id is not None and created_topic_title == topic_name:
print(f"{topic_name}:{created_topic_id}")
else:
print(f"No forum topic with the name '{topic_name}' was created in the provided updates.")
#print(f"Forum topic created: {result}")
async def main():
async with TelegramClient('session1', api_id, api_hash) as client:
await create_forum_topic(client, "ENTER_YOUR_GROUP_ID", 'Test-latest2')
if __name__ == "__main__":
import asyncio
asyncio.run(main())