Un bot qui récupère une image random en local et la publie
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

136 lines
4.3KB

  1. #!/usr/bin/python3
  2. # coding: utf-8
  3. # -*- coding: utf-8 -*-
  4. from mastodon import Mastodon, StreamListener
  5. from TootHTMLParser import TootHTMLParser
  6. import requests, os, random, sys, time, json, logging, argparse
  7. from logging.handlers import RotatingFileHandler
  8. from pprint import pprint
  9. # Mastodon Stream Listener defines functions to react when something happens on Mastodon. We inherit it.
  10. class BotListener(StreamListener):
  11. def __init__(self, mastodon):
  12. print("init")
  13. StreamListener.__init__(self)
  14. self.mastodon = mastodon
  15. pprint(vars(mastodon.stream_user(StreamListener)))
  16. def handle_mention(self, status):
  17. log.debug('Got a mention!')
  18. def on_notification(self, notification):
  19. log.debug("here")
  20. for thread in self.threads:
  21. if(not thread.is_alive()):
  22. logging.info("removing thread" + str(thread))
  23. self.threads.remove(thread)
  24. #We react to mentions only
  25. if(notification['type'] != 'mention'):
  26. log.info("nevermind, it's not a mention")
  27. return
  28. #So there is a toot !
  29. status = notification['status']
  30. #And there is a text in this toot. But it is mixed with HTML we don't want so we get rid of it.
  31. content = str(status["content"])
  32. parser = TootHTMLParser()
  33. parser.feed(content)
  34. content = (parser.txt).lower()
  35. logging.info(content)
  36. atUser = status["account"]["acct"]
  37. userInfo = self.associateToUser(atUser)
  38. #If the toot is not in answer to a drawing
  39. answerTo = status["in_reply_to_id"]
  40. def get_parameter( parameter, file_path ):
  41. # Check if secrets file exists
  42. if not os.path.isfile(file_path):
  43. log.error("File %s not found, exiting."%file_path)
  44. sys.exit(0)
  45. # Find parameter in file
  46. with open( file_path ) as f:
  47. for line in f:
  48. if line.startswith( parameter ):
  49. return line.replace(parameter + ":", "").strip()
  50. # Cannot find parameter, exit
  51. log.critical(file_path + " Missing parameter %s "%parameter)
  52. sys.exit(0)
  53. def post_img(mastodon, text, visibility, logging):
  54. file = random.choice(os.listdir(img_path+"/"))
  55. image_byte = open(img_path+"/"+file, "rb").read()
  56. if file[-3:] == "jpe":
  57. mime = "image/jpeg"
  58. else :
  59. if file[-3:] == "jpg":
  60. mime = "image/jpeg"
  61. else :
  62. if file[-3:] == "png":
  63. mime = "image/png"
  64. else :
  65. if file[-3:] == "gif":
  66. mime = "image/gif"
  67. media_dict = mastodon.media_post(image_byte, mime)
  68. mastodon.status_post("", None, media_ids=[media_dict], sensitive=True, visibility='', spoiler_text="#NSFW")
  69. def init(config, secrets):
  70. log = logging.getLogger()
  71. log.setLevel(logging.DEBUG)
  72. formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s')
  73. file_handler = RotatingFileHandler('activity.log', 'a', 1000000, 1)
  74. file_handler.setLevel(logging.DEBUG)
  75. file_handler.setFormatter(formatter)
  76. log.addHandler(file_handler)
  77. stream_handler = logging.StreamHandler()
  78. stream_handler.setLevel(logging.DEBUG)
  79. log.addHandler(stream_handler)
  80. uc_client_id = get_parameter("client_id", secrets)
  81. uc_client_secret = get_parameter("client_secret", secrets)
  82. uc_access_token = get_parameter("access_token", secrets)
  83. mastodon_hostname = get_parameter("mastodon_hostname", secrets)
  84. img_path = get_parameter("img_path", config)
  85. mastodon = Mastodon(
  86. client_id = uc_client_id,
  87. client_secret = uc_client_secret,
  88. access_token = uc_access_token,
  89. api_base_url = 'https://' + mastodon_hostname,
  90. )
  91. def run(mastodon, log):
  92. log.info("Start streaming")
  93. listener = BotListener(mastodon, logging)
  94. mastodon.stream_user(listener)
  95. #post_img(mastodon, "NSFW", 1)
  96. def main():
  97. config_file = "config.txt"
  98. secrets_filepath = "secrets/secrets.txt"
  99. init(config_file, secrets_filepath)
  100. parser = argparse.ArgumentParser()
  101. parser.add_argument('command', type=str, choices=['img', 'stream'])
  102. args = parser.parse_args()
  103. if args.command == 'img':
  104. post_img(mastodon, "NSFW", 1, log)
  105. elif args.command == 'stream':
  106. run(mastodon, log)
  107. main()