mastodon2telegram.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #!/usr/bin/env python3
  2. import requests
  3. import json
  4. import telegram
  5. import re
  6. from time import sleep
  7. from telegram.error import NetworkError, Unauthorized
  8. telegram_token= ""
  9. telegram_channel=""
  10. profile_id=""
  11. telegram_bot = telegram.Bot(telegram_token)
  12. response = requests.get("https://mastodon.bida.im/api/v1/accounts/"+profile_id+"/statuses")
  13. last_id_filename = "/var/db/mastodon2telegram/"+profile_id+"_last_id_telegram.txt"
  14. last_id_file = open(last_id_filename, 'r')
  15. last_id = int(last_id_file.read())
  16. last_id_file.close()
  17. statuses = json.loads(response.text)
  18. statuses = sorted(statuses, key=lambda k: k['created_at'])
  19. print(last_id)
  20. for status in list(filter(lambda x: int(x["id"]) > last_id, list(filter(lambda x: x["in_reply_to_account_id"] == None, statuses)))):
  21. id = int(status["id"])
  22. print(status["created_at"])
  23. print(id)
  24. if last_id < id:
  25. last_id = id
  26. content = status["content"]
  27. if content != "":
  28. content = re.sub(r'<p>', '\n', content)
  29. content = re.sub(r'</p>', '\n', content)
  30. content = re.sub(r'<br />', '\n', content)
  31. content = re.sub(r'<(/?)(span)([^>]+)?>', '', content)
  32. content = re.sub(r'<a [^>]+ rel=\"tag\">#([^>]+)<\/a>', r'#\1', content)
  33. content = content.replace("&apos;", "'")
  34. for emoji in status["emojis"]:
  35. content = content.replace(":"+emoji["shortcode"]+":", "")
  36. print(content)
  37. try:
  38. telegram_bot.send_message(chat_id=telegram_channel, text=content, parse_mode=telegram.ParseMode.HTML, disable_web_page_preview="true")
  39. except Exception as err:
  40. print("aiai", err)
  41. for media in list(filter(lambda x: x["type"] == "image", status["media_attachments"])):
  42. try:
  43. telegram_bot.send_photo(chat_id=telegram_channel, photo=media["url"])
  44. sleep(10)
  45. except Exception:
  46. print("mediaiaia")
  47. sleep(10)
  48. print("-----------")
  49. last_id_file = open(last_id_filename, 'w')
  50. last_id_file.write(str(last_id))
  51. last_id_file.close()