welcomebot.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from mastodon import Mastodon
  2. from dotenv import load_dotenv
  3. from pathlib import Path
  4. import os
  5. import time
  6. load_dotenv()
  7. INSTANCE_BASE = os.getenv('INSTANCE_BASE')
  8. CLIENT_ID = os.getenv('CLIENT_ID')
  9. CLIENT_SECRET = os.getenv('CLIENT_SECRET')
  10. ACCESS_TOKEN = os.getenv('ACCESS_TOKEN')
  11. WELCOME_MESSAGE = os.getenv('WELCOME_MESSAGE', 'Welcome to the instance, @{username}!').replace("\\n","\n")
  12. MESSAGE_VISIBILITY = os.getenv('MESSAGE_VISIBILITY', 'unlisted')
  13. WAIT_TIME = int(os.getenv('WAIT_TIME', 300))
  14. IS_DOCKER = os.getenv('IS_DOCKER', False)
  15. def contains_local_account(accounts):
  16. for account in accounts:
  17. if account.username == account.acct:
  18. return True
  19. return False
  20. def is_local_account(account):
  21. return account.username == account.acct
  22. def send_welcome_message(mastodon, account):
  23. formatted_message = WELCOME_MESSAGE.format(username=account.username, useracct=account.acct)
  24. mastodon.status_post(formatted_message)
  25. last_id_file = Path('.') / 'last_id.txt'
  26. last_id = 0
  27. if IS_DOCKER:
  28. last_id_file = Path('/data') / 'last_id'
  29. if last_id_file.is_file():
  30. with open(str(last_id_file)) as f:
  31. last_id = int(f.read())
  32. print('Botvenon is starting...')
  33. print('Welcoming any users after id %d' % last_id)
  34. mastodon = Mastodon(
  35. client_id=CLIENT_ID,
  36. client_secret=CLIENT_SECRET,
  37. access_token=ACCESS_TOKEN,
  38. api_base_url=INSTANCE_BASE)
  39. user = mastodon.account_verify_credentials() # Get the current user
  40. followers = mastodon.account_followers(user) # Get the latest followers
  41. # print(
  42. # f'''Followed by: {account.username}
  43. # (Acct value: {account.acct}, id: {account.id})''')
  44. while True:
  45. for account in mastodon.account_followers(user):
  46. if is_local_account(account) and account.id > last_id and not account.bot:
  47. last_id = account.id
  48. with open(str(last_id_file), 'w+') as f:
  49. f.write(str(last_id))
  50. print('Welcoming %s...' % account.username)
  51. send_welcome_message(mastodon, account)
  52. time.sleep(WAIT_TIME)