I usually share some links of Twitter(it is known as X now but I still call it Twitter) in Telegram, but for some reason the previews doesn't work well most of the times.
One solution was to edit a Twitter link so I can use vxtwitter.com instead of twitter.com, this provides better previews but doing it that way is too manual so I made a bot to detect when I share a Twitter link and edit the message to use vxtwitter.com instead.
The bot uses the library telethon, it's a really easy to use python library. Also it has great documentation.
This is the complete code.
from telethon import TelegramClient, events
# get credentials from https://my.telegram.org, under API Development
# section, then fill the following section
api_id = 123
api_hash = "api hash"
# The first parameter is the .session file name (absolute paths allowed)
client = TelegramClient("my-bot", api_id, api_hash)
# outgoing=True is important so we only listen to our own messages,
# otherwise this will listen to all the messages received, direct
# messages and group messages
@client.on(events.NewMessage(outgoing=True))
async def rewrite_twitter_links(event):
if "x.com" in event.raw_text:
reply_text = event.raw_text.replace("x.com", "vxtwitter.com")
# we must use the correct object to be able to edit the
# message, otherwise we'll get an error
if event.is_group:
source = event.chat_id
else:
source = event.sender_id
await client.edit_message(
source, event.message.id, reply_text, link_preview=True
)
client.start()
client.run_until_disconnected()
The code is simple, it connect to Telegram API using a "personal bot", this means it will act on your behalf. It will detect when the message has a x.com link and it will replace it(making an edit) with vxtwitter.com so it will be have a nice preview :)
This can be extended to do another nice things, for example: TikTok doesn't allow to see videos in mobile at least you have their app installed. In case someone send me a TikTok link I automatically respond with a preview message using vm.vxtiktok.com so I can see the video inside Telegram without having to install the app :).
The code to do that is:
@client.on(events.NewMessage(incoming=True))
async def rewrite_tiktok_links(event):
# ignore group messages
if event.is_group:
return
if "vm.tiktok.com" in event.raw_text:
await event.reply(event.raw_text.replace("tiktok.com", "vxtiktok.com"))
In this case we respond only to a direct messages, that's why the early return when event.is_group
is true.