Get Telegram Topic ID (message_thread_id(topic)) without messages
Good day,
To obtain the Telegram topic ID without any messages, you can use the `channels.createForumTopic` method in Telegram Bots. Here is the code snippet for achieving this:
```python
from telethon import TelegramClient
from telethon.tl.functions.channels import GetFullChannelRequest, CreateForumTopicRequest
from telethon.tl.types import InputChannel, MessageActionTopicCreate
import asyncio
api_id = # Your API ID
api_hash = # Your 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.")
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())
```
You can use the mentioned method in your bot to create a forum topic in a channel and retrieve the ID of the created topic. The code uses the `telethon` library to interact with the Telegram API.
Please note that you need to replace `ENTER_YOUR_GROUP_ID` with the actual ID of the group or channel where you want to create the forum topic. Additionally, provide your own `api_id` and `api_hash`.
Feel free to modify the code according to your requirements and add additional parameters to the `CreateForumTopicRequest` if necessary.
Hope this helps!