tg2toot/tgchannel2toot.py
2023-12-12 07:46:30 -05:00

85 lines
1.9 KiB
Python

#!/usr/bin/python3
# Released under GPLv3+ License
# Danial Behazdi <dani.behzi@ubuntu.com>, 2018-2021
"""
Listen for a new post on a Telegram channel
And post them on Mastodon
"""
import os
import pyrogram
import mastodon
import config
def splitext(text: str):
"""
split text into parts
"""
limit = config.character_limit
result = [
text[limit * part : limit * (part + 1)]
for part in range(len(text) // limit + 1)
]
return result
def get_text_and_media(message):
"""
returns the text and media from post
"""
text = " "
media = None
if hasattr(message, "media"):
text = message.caption
media = message.download()
elif hasattr(message, "text"):
text = message.text
return splitext(text), media
def connect():
"""
initialize mastodon
"""
mast = mastodon.Mastodon(
access_token=config.access_token, api_base_url=config.instance
)
return mast
def main():
"""
main function
"""
telegram = pyrogram.Client(
"tgchannel2toot", api_id=config.api_id, api_hash=config.api_hash
)
mastodon = connect()
@telegram.on_message()
def check_message(client, message):
chat = message.chat
if chat.type==pyrogram.enums.ChatType.CHANNEL:
if chat.username == config.channel_id:
text, media = get_text_and_media(message)
if media:
mid = mastodon.media_post(media)
os.remove(media)
else:
mid = None
post = mastodon.status_post(text[0], media_ids=mid)
for part in range(1, len(text)):
post = mastodon.status_post(
text[part], in_reply_to_id=post["id"]
)
telegram.run()
if __name__ == "__main__":
main()