Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Source code for Mastodon's nicenessbot
from mastodon import Mastodon
from bs4 import BeautifulSoup
from random import randint
# Connect to Mastodon with bot token
mastodon = Mastodon(
access_token = 'REPLACE ME',
api_base_url = 'REPLACE ME'
# List of prebuilt messages to send
messages = (
"Look at the sky. Someone is looking at it and thinking of you " + u"\u2665",
"Reminder that you are loved and never alone :)",
u"\u2665" + " You are beloved! " + u"\u2665",
"Someone loves you <3",
"Life is beautiful magical fantastical, and so you are <3",
"Someone wants you to know that they'll always be here for you",
"Someone who really likes you wanted to remind you of it :)"
# Retrieve id of the latest notification we checked
file = open('last_id', 'r')
except FileNotFoundError:
last_id = "None"
last_id ="\n")
# Retrieve all the recent notifications
notifications = mastodon.notifications(since_id=last_id)
for n in notifications:
# We ignore anything that's not a mention because it doesn't contain a post
if n['type'] == "mention":
# The bot is meant to be anonymous so only allow directs
if n['status']['visibility'] == "direct":
# Mentions data are HTML paragraphs so we delete everything between <> to clean it up
content = BeautifulSoup(n['status']['content'], "html.parser").get_text()
# Replace every dual spaces so we end with a string divided by single whitespaces
while ' ' in content:
content = content.replace(' ', ' ')
content = content.split(" ")
# Retrieve index of the !nice command to know where should look for the the user and server
commandstart = content.index("!nice")
except ValueError:
mastodon.status_reply(n['status'], "Your message does not appear to have the required !nice command.\n\nIt should have the following syntax:\n!nice user server")
# Build the target full name based on the mention we received
target = "@" + content[commandstart+1] + "@" + content[commandstart+2]
user = "@" + n['account']['acct']
if user == target:
mastodon.status_reply(n['status'], "The most important person that you should ever love is yourself. You are amazing! ❤")
bio = mastodon.account_search(target)[0]
except IndexError:
mastodon.status_reply(n['status'], "We couldn't find an account with that handle but we still tried to forward the request.")
mastodon.toot(target + " " + messages[randint(0,6)])
if "nobot" in bio['note']:
mastodon.status_reply(n['status'], "Sorry but the targeted user does not want to interact with bots")
mastodon.toot(target + " " + messages[randint(0,6)])
# We write as the new last_id the most recent notification, which is always index 0
file = open('last_id', 'w')
except IndexError:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment