Ejemplo n.º 1
0
    def initiate_auth(self, id_url, callback_uri, redir):
        try:
            instance = self._get_instance(id_url)
            client_id, client_secret = mastodon.Mastodon.create_app(
                api_base_url=instance,
                client_name=self._name,
                website=self._homepage,
                scopes=['read:accounts'],
                redirect_uris=callback_uri,
            )
        except Exception as err:  # pylint:disable=broad-except
            return disposition.Error(f"Failed to register client: {err}",
                                     redir)

        client = mastodon.Mastodon(api_base_url=instance,
                                   client_id=client_id,
                                   client_secret=client_secret)

        state = self._token_store.put(
            (instance, client_id, client_secret, time.time(), redir))

        # mastodon.py doesn't support a state parameter for some reason, so we
        # have to add it ourselves
        url = '{}&{}'.format(
            client.auth_request_url(
                redirect_uris=callback_uri,
                scopes=['read:accounts'],
            ), urllib.parse.urlencode({'state': state}))

        return disposition.Redirect(url)
Ejemplo n.º 2
0
    def cred_init(
        self,
        *,
        secrets_dir: str,
        log: Logger,
        bot_name: str = "",
    ) -> None:
        """Initialize what requires credentials/secret files."""
        super().__init__(secrets_dir=secrets_dir, log=log, bot_name=bot_name)

        self.ldebug("Retrieving ACCESS_TOKEN ...")
        with open(path.join(self.secrets_dir, "ACCESS_TOKEN")) as f:
            ACCESS_TOKEN = f.read().strip()

        # Instance base url optional.
        self.ldebug("Looking for INSTANCE_BASE_URL ...")
        instance_base_url_path = path.join(self.secrets_dir,
                                           "INSTANCE_BASE_URL")
        if path.isfile(instance_base_url_path):
            with open(instance_base_url_path) as f:
                self.instance_base_url = f.read().strip()
        else:
            self.ldebug(
                "Couldn't find INSTANCE_BASE_URL, defaulting to mastodon.social."
            )
            self.instance_base_url = "https://mastodon.social"

        self.api = mastodon.Mastodon(access_token=ACCESS_TOKEN,
                                     api_base_url=self.instance_base_url)
        self.html_re = re.compile("<.*?>")
Ejemplo n.º 3
0
def setup_mastodon(config):
    logging.info("---------- Initialising Mastodon")
    instance = mastodon.Mastodon(
        access_token = config['MASTODON']['access_token'],
        api_base_url = config['MASTODON']['url']
    )
    return instance
Ejemplo n.º 4
0
def _api(access_token='__MASTODON_PY_TEST_ACCESS_TOKEN'):
    import mastodon
    return mastodon.Mastodon(api_base_url='http://localhost:3000',
                             client_id='__MASTODON_PY_TEST_CLIENT_ID',
                             client_secret='__MASTODON_PY_TEST_CLIENT_SECRET',
                             access_token=access_token,
                             mastodon_version="2.1.0")
Ejemplo n.º 5
0
 def readConfig(self):
     try:
         config = open(os.path.expanduser("~/.fedifollowautoresponder"))
         parsed_config = json.load(config)
     except:
         self.buildConfig()
         return
     self.response = parsed_config['response']
     self.client_id = parsed_config['client_id']
     self.client_secret = parsed_config['client_secret']
     self.auth_key = parsed_config['auth_key']
     self.base_url = parsed_config['base_url']
     try:
         self.follow_requests_seen = parsed_config['follow_requests_seen']
     except KeyError:
         self.follow_requests_seen = []
     self.api = mastodon.Mastodon(client_id=self.client_id,
                                  client_secret=self.client_secret,
                                  api_base_url=self.base_url,
                                  access_token=self.auth_key)
     try:
         self.api.follow_requests()
     except Exception as e:
         print 'Authentication error.  Please try logging in again.'
         self.auth_key = ''
         self.buildConfig()
Ejemplo n.º 6
0
def create_mastodon(mastodon_account):
    return mastodon.Mastodon( \
        api_base_url = mastodon_account['api_base_url'], \
        client_id = mastodon_account['client_id'], \
        client_secret = mastodon_account['client_secret'], \
        access_token = mastodon_account['access_token'] \
    )
Ejemplo n.º 7
0
def login(access_token):
    '''
    pawooにログインする。必要なら認証する
    '''
    objMstdn = None
    retry = True

    while retry:
        # オブジェクト作成
        objMstdn = mastodon.Mastodon(client_id=CLIENT_ID,
                                     client_secret=CLIENT_SECRET,
                                     access_token=access_token,
                                     api_base_url="https://pawoo.net")
        # ログインできてるかテスト
        try:
            objMstdn.account_verify_credentials()
            retry = False
        except MastodonError:
            # Oauth認証
            authurl = objMstdn.auth_request_url(scopes=['read', 'write'])
            webbrowser.open_new(authurl)
            auth_code = input("Input Authorization Code >>")
            access_token = objMstdn.log_in(code=auth_code,
                                           scopes=['read', 'write'])

        # loop

    return objMstdn
Ejemplo n.º 8
0
def new_credentials_from_mastodon(group_name, config_dir, config):
    """Register tootgroup.py at a Mastodon server and get user credentials.
    
    "group_name" points to the current groups settings in the config file

    "config_dir" directory where the config and credentials are stored

    "config" the configuration as read in from configparser
    
    This will be run if tootgroup.py is started for the first time, if its
    configuration files have been deleted or if some elements of the
    configuration are missing.
    """
    # Register tootgroup.py app at the Mastodon server
    try:
        mastodon.Mastodon.create_app(
            "tootgroup.py",
            api_base_url=config[group_name]["mastodon_instance"],
            to_file=config_dir + config[group_name]["client_id"])
        # Create Mastodon API instance
        masto = mastodon.Mastodon(
            client_id=config_dir + config[group_name]["client_id"],
            api_base_url=config[group_name]["mastodon_instance"])
    except Exception as e:
        print("")
        print(
            "\n##################################################################"
        )
        print(
            "The Mastodon instance URL is wrong or the server does not respond."
        )
        print("See the error message for more details:")
        print(e)
        print("")
        print("tootgroup.py will exit now. Run it again to try once more!")
        print(
            "##################################################################\n"
        )
        sys.exit(0)

    # Log in once with username and password to get an access token for future logins.
    # Ask until login succeeds or at most 3 times before the skript gives up.
    i = 0
    while i < 3:
        i += 1
        try:
            masto.log_in(
                input("Username (e-Mail) to log into Mastodon Instance: "),
                input("Password: "******"access_token"])
            break
        except Exception:
            print("\nUsername and/or Password did not match!")
            if i < 3:
                print("Please enter them again.\n")
            else:
                print(
                    "tootgroup.py will exit now. Run it again to try once more!\n"
                )
                sys.exit(0)
Ejemplo n.º 9
0
def botStart(serverAddress, serverPort, client_id, client_secret, access_token,
             base_url):
    # Create a Mastodon client
    client = mastodon.Mastodon(client_id=client_id,
                               client_secret=client_secret,
                               access_token=access_token,
                               api_base_url=base_url)
    pass
Ejemplo n.º 10
0
def _api(access_token='__MASTODON_PY_TEST_ACCESS_TOKEN', version="3.1.1", version_check_mode="created"):
    import mastodon
    return mastodon.Mastodon(
            api_base_url='http://localhost:3000',
            client_id='__MASTODON_PY_TEST_CLIENT_ID',
            client_secret='__MASTODON_PY_TEST_CLIENT_SECRET',
            access_token=access_token,
            mastodon_version=version,
            version_check_mode=version_check_mode)
Ejemplo n.º 11
0
 def login(self):
     m = mastodon.Mastodon(
         client_id=self.client_id,
         api_base_url=self.config['muser']['server']
     )
     m.log_in(
         self.config['muser']['email'],
         self.config['muser']['password']
     )
     return m
Ejemplo n.º 12
0
    def check_callback(self, url, get, data):
        try:
            (instance, client_id, client_secret, when,
             redir) = self._token_store.pop(get['state'])
        except (KeyError, ValueError):
            return disposition.Error("Invalid transaction", '')

        if 'error' in get:
            return disposition.Error(
                "Error signing into instance: " +
                get.get('error_description', get['error']), redir)

        if time.time() > when + self._timeout:
            return disposition.Error("Login timed out", redir)

        client = mastodon.Mastodon(api_base_url=instance,
                                   client_id=client_id,
                                   client_secret=client_secret)

        try:
            access_token = client.log_in(
                code=get['code'],
                redirect_uri=url,
                scopes=['read:accounts'],
            )
        except KeyError as err:
            return disposition.Error(f"Missing {err}", redir)
        except Exception as err:  # pylint:disable=broad-except
            return disposition.Error(f"Error signing into instance: {err}",
                                     redir)

        result = self._get_identity(instance, client.me(), redir)

        # clean up after ourselves
        # mastodon.py does not currently support the revoke endpoint; see
        # https://github.com/halcy/Mastodon.py/issues/217
        try:
            request = requests.post(instance + '/oauth/revoke',
                                    data={
                                        'client_id': client_id,
                                        'client_secret': client_secret,
                                        'token': access_token
                                    },
                                    headers={
                                        'Authorization':
                                        f'Bearer {access_token}',
                                        'User-Agent':
                                        utils.get_user_agent(self._homepage),
                                    })
            LOGGER.info("OAuth token revocation: %d %s", request.status_code,
                        request.text)
        except Exception as err:  # pylint:disable=broad-except
            LOGGER.warning("Token revocation failed: %s", err)

        return result
Ejemplo n.º 13
0
 def _get_mastodon_client(self, name):
     """Get a mastodon client."""
     if name not in self._cached_mastodon:
         conf = self.config["mastodon"][name]
         self._cached_mastodon[name] = mastodon.Mastodon(
             access_token=conf["access_token"],
             api_base_url=conf["url"],
             ratelimit_method="throw",
             version_check_mode="none",
         )
     return self._cached_mastodon[name]
Ejemplo n.º 14
0
    def initApi(self, keys):
        pos = self.user.find('@', 1)  # The first character can be @
        if pos > 0:
            self.base_url = f"https://{self.user[pos:]}"
            #self.user = self.user[:pos]
        else:
            self.base_url = 'https://mastodon.social'

        logging.debug(f"Mastodon user:  {self.user} base: {self.base_url}")
        client = mastodon.Mastodon(access_token=keys[0],
                                   api_base_url=self.base_url)
        return client
Ejemplo n.º 15
0
def get_client(
    client_id,
    client_secret,
    access_token,
    api_base_url,
):
    return mastodon.Mastodon(
        client_id=client_id,
        client_secret=client_secret,
        access_token=access_token,
        api_base_url=api_base_url,
    )
Ejemplo n.º 16
0
def get_username(client_id, client_secret, access_token, instance):
    try:
        masto_session = mastodon.Mastodon(client_id=client_id,
                                          client_secret=client_secret,
                                          access_token=access_token,
                                          api_base_url='https://' + instance)
        masto_acct_info = masto_session.account_verify_credentials()
        username = masto_acct_info['username']
        return username
    except mastodon.MastodonError:
        print("Something happened! (Something happened!)")
        exit(2)
Ejemplo n.º 17
0
def get_mastodon(config_path):
    """Returns a Mastodon connection object."""
    p = pathlib.Path(config_path)

    instance = get_instance(p)

    if instance is None or not is_configured(config_path):
        raise RuntimeError("You must call generate_config first")

    return mastodon.Mastodon(client_id=p.joinpath(CLIENTCRED_FILE),
                             api_base_url=instance,
                             access_token=p.joinpath(USERCRED_FILE))
Ejemplo n.º 18
0
    def log_in_user(self, email, password, app_creds):
        """Log in a user to the instance.

        Args:
            email: str, the user's registration email.
            password: str, the user's password.
            app_creds: (str, str), the pair of id + secret assigned to the app.

        Returns:
            str, the user's secret OAuth token.
        """
        (app_id, secret) = app_creds
        api = mastodon.Mastodon(app_id, secret, api_base_url=self.instance)
        return api.log_in(email, password, scopes=self.scopes)
Ejemplo n.º 19
0
def get_session_and_login_url(instance, client_id, client_secret, scopes):
    try:
        masto_auth = mastodon.Mastodon(client_id=client_id,
                                       client_secret=client_secret,
                                       api_base_url='https://' + instance)
        login_url = masto_auth.auth_request_url(client_id=client_id,
                                                scopes=scopes,
                                                force_login=True)
        return masto_auth, login_url
    except mastodon.MastodonNetworkError:
        print("Couldn't connect to the instance for some reason, bailing...")
        exit(1)
    except mastodon.MastodonError:
        print("Something happened! (Something happened!)")
        exit(2)
Ejemplo n.º 20
0
def main():
    engine = create_engine(os.environ.get('DATABASE_URL'))
    Session = sessionmaker(engine)

    session = Session()

    api = mastodon.Mastodon(
        api_base_url='https://qdon.space',
        client_id=os.environ.get('MASTODON_CLIENT_KEY'),
        client_secret=os.environ.get('MASTODON_CLIENT_SECRET'),
        access_token=os.environ.get('MASTODON_ACCESS_TOKEN'))

    handler = StreamHandler(api, session)

    api.stream_user(handler)
Ejemplo n.º 21
0
    def get_api_client(self, user_token, app_creds):
        """Obtain the final pleroma/mastodon API client.

        Args:
            user_token: str, the user's OAuth access token.
            app_creds: (str, str), the pair of id + secret assigned to the app.

        Returns:
            A properly authenticated Mastodon Object.
        """
        (app_id, secret) = app_creds
        return mastodon.Mastodon(app_id,
                                 secret,
                                 user_token,
                                 api_base_url=self.instance)
Ejemplo n.º 22
0
 def buildConfig(self):
     while self.base_url == '':
         self.base_url = raw_input(
             'Mastodon API-compatible instance (https://mastodon.social for example): '
         )
         try:
             (self.client_id,
              self.client_secret) = mastodon.Mastodon.create_app(
                  'Fediverse follow request autoresponder 201902202200',
                  scopes=['read:follows', 'write:statuses'],
                  api_base_url=self.base_url)
         except Exception as e:
             self.base_url = ''
             print 'Failed to connect to instance.  Please double check that it is spelled correctly.'
             print str(e)
             print '\n'
     self.api = mastodon.Mastodon(client_id=self.client_id,
                                  client_secret=self.client_secret,
                                  api_base_url=self.base_url)
     while self.auth_key == '':
         self.auth_key = raw_input(
             'Please go to this URL to authorize the app to access your account, and copy and paste the code it gives below.\n%s\nCode: '
             % self.api.auth_request_url(
                 client_id=self.client_id,
                 scopes=['read:follows', 'write:statuses']))
         try:
             self.auth_key = self.api.log_in(
                 code=self.auth_key,
                 scopes=['read:follows', 'write:statuses'])
         except Exception as e:
             self.auth_key = ''
             print 'Unable to log in.'
             print str(e)
             print '\n'
     response = raw_input(
         'Current response message: %s\nEnter new message.  %%s will be replaced with the username of the requestor.  If you need a %%, then use %%%%.  Blank to keep the current message.\n'
         % self.response)
     if response.strip() != '':
         self.response = response
     self.writeConfig()
     print 'Configuration complete and successfully written to disk.'
Ejemplo n.º 23
0
def create_client(username: str,
                  password: str,
                  domain: str = 'botsin.space') -> mastodon.Mastodon:
    api = 'https://{}'.format(domain)

    # app creation
    if not os.path.exists(APP_FILE):
        mastodon.Mastodon.create_app('Big Meow',
                                     to_file=APP_FILE,
                                     api_base_url=api)

    # login
    secrets = None
    if os.path.exists(SECRETS_FILE):
        secrets = SECRETS_FILE
    client = mastodon.Mastodon(api_base_url=api,
                               client_id=APP_FILE,
                               access_token=secrets)
    if secrets is None:
        client.log_in(username, password, to_file=SECRETS_FILE)

    return client
Ejemplo n.º 24
0
def run():
    parser = argparse.ArgumentParser(description='Guest Curator Bot.')
    parser.add_argument('--config',
                        '-c',
                        type=argparse.FileType('r'),
                        default='config.yml',
                        help='config file location')

    args = parser.parse_args()
    config = yaml.load(args.config)
    args.config.close()

    api = mastodon.Mastodon(client_id=config.get('client_key'),
                            client_secret=config.get('client_secret'),
                            access_token=config.get('access_token'),
                            api_base_url=config.get('instance'))

    try:
        guest_curator = GuestCurator(api)
        api.user_stream(guest_curator)
    except KeyboardInterrupt:
        print("cleaning up...")
        guest_curator.cleanup()
Ejemplo n.º 25
0
#!/usr/bin/env python3
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import mastodon
import random, re, json
import functions
from bs4 import BeautifulSoup

cfg = json.load(open('config.json', 'r'))
threads = {}

client = mastodon.Mastodon(client_id=cfg['client']['id'],
                           client_secret=cfg['client']['secret'],
                           access_token=cfg['secret'],
                           api_base_url=cfg['site'])


def extract_toot(toot):
    text = functions.extract_toot(toot)
    text = re.sub(r"^@[^@]+@[^ ]+\s*", r"", text)  #remove the initial mention
    text = text.lower(
    )  #treat text as lowercase for easier keyword matching (if this bot uses it)
    return text


class ReplyListener(mastodon.StreamListener):
    def on_notification(self, notification):  #listen for notifications
        if notification['type'] == 'mention':  #if we're mentioned:
            acct = "@" + notification['account']['acct']  #get the account's @
Ejemplo n.º 26
0
target_url = 'https://www.pixiv.net/bookmark.php?type=user&rest=show&p='

# 全てのフォローユーザーのユーザIDを取得
following_users_id = []
for i in range(1, pages + 1):
    print(target_url + str(i))
    browser.open(target_url + str(i))
    following_users = browser.find(class_='members')
    for user in following_users.find_all("input"):
        following_users_id.append(user.get("value"))
    sleep(3)  # ページを移動したら一時待機する(マナー)
#ここまで元ソースコピペ

#pawooにログイン
pawoo = mastodon.Mastodon(client_id="my_clientcred_pawoo.txt",
                          access_token="my_usercred_pawoo.txt",
                          api_base_url="https://pawoo.net")

#Pawoo紐づけてるアカウントを抽出してフォロー
for i in range(0, following_users_num):
    json_result = aapi.user_detail(following_users_id[i])
    if (json_result.profile.pawoo_url != None):
        print(json_result.user.name)
        pawoo_url = requests.get(json_result.profile.pawoo_url)
        if (pawoo_url.status_code != 200):
            print("Not found userpage")
            continue
        pawoo_id = pawoo_url.url.lstrip("https://pawoo.net/") + "@pawoo.net"
        print(pawoo_id)
        try:
            pawoo_user_detail = pawoo.account_search(pawoo_id, limit=1)
Ejemplo n.º 27
0
#!/usr/bin/env python3
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import mastodon
import os, random, re
import create
from bs4 import BeautifulSoup

api_base_url = "https://botsin.space"
client = mastodon.Mastodon(
        client_id="clientcred.secret", 
        access_token="usercred.secret", 
        api_base_url=api_base_url)

def extract_toot(toot):
	#copied from main.py, see there for comments
	soup = BeautifulSoup(toot, "html.parser")
	for lb in soup.select("br"):
		lb.insert_after("\n")
		lb.decompose()
	for p in soup.select("p"):
		p.insert_after("\n")
		p.unwrap()
	for ht in soup.select("a.hashtag"):
		ht.unwrap()
	for link in soup.select("a"):
		link.insert_after(link["href"])
		link.decompose()
	text = map(lambda a: a.strip(), soup.get_text().strip().split("\n"))
Ejemplo n.º 28
0
def main():
    """Execution starts here"""

    # Read commandline arguments and flags from input
    commandline_arguments = tootgroup_tools.commandline_arguments.parse_arguments(
    )

    # if the "--version" argument has been given, show version and exit.
    if commandline_arguments["show_version"]:
        tootgroup_tools.version.print_version()
        sys.exit(0)

    # Get the configuration storage location
    config_store = tootgroup_tools.configuration_management.setup_configuration_store(
    )

    # Get the Mastodon/Pleroma account handle the script is running for.
    config_store["group_name"] = commandline_arguments["group_name"]
    group_name = config_store["group_name"]

    # Get and validate configuration from the config file.
    my_config = tootgroup_tools.configuration_management.parse_configuration(
        config_store)

    # If the "catch-up" commandline argument has been given, reset the last seen
    # ID so that tootgroup.py only updates its according config value without
    # retooting anything.
    if commandline_arguments["catch_up"]:
        my_config[group_name]["last_seen_id"] = "catch-up"

    # Create Mastodon API instance.
    masto = mastodon.Mastodon(
        client_id=config_store["directory"] +
        my_config[group_name]["client_id"],
        access_token=config_store["directory"] +
        my_config[group_name]["access_token"],
        api_base_url=my_config[group_name]["mastodon_instance"],
    )

    try:
        # Get the group account information.
        # This connects to the Mastodon or Pleroma server for the first time at
        # every tootgroup.py's run.
        my_account = {
            "username": masto.account_verify_credentials().username,
            "id": masto.account_verify_credentials().id,
            "group_member_ids": [],
        }
    except Exception as ex:
        print("")
        print("\n########################################################")
        print("tootgroup.py could not connect to the Mastodon or Pleroma")
        print("instance. If you know that it is running, there might be a")
        print("problem with your local configuration. Check the error")
        print("message for more details:")
        print(ex)
        print("\nYou can always try to delete tootgroup.py's config file")
        print("and re-run the script for a new setup.")
        print("########################################################\n")
        sys.exit(0)

    # Get group member IDs. They can not be fetched directly when
    # connecting to the Mastodon server.
    #
    # limit=sys.maxsize is set here because Pleroma only returns 20 Member if
    # the standard limit=None value is used!
    for member in masto.account_following(my_account["id"], limit=sys.maxsize):
        my_account["group_member_ids"].append(member.id)

    # Do we accept direct messages, public retoots, both or none? This
    # can be set in the configuration.
    accept_direct_messages = my_config[group_name].getboolean("accept_DMs")
    accept_retoots = my_config[group_name].getboolean("accept_retoots")
    dm_visibility = my_config[group_name]["dm_visibility"]

    # Get all new notifications up to a maximum number set here.
    # Defaults to 100 and has to be changed in the code if really desired.
    # Use the ID of the last seen notification for deciding what is new.
    notification_count = 0
    max_notifications = 100
    max_notification_id = None
    latest_notification_id = 0
    my_notifications = []
    get_more_notifications = True

    # Get notifications. Stop if either the last known notification ID or
    # the maximum number is reached. Chunk size is limited to 40 by default
    # in Mastodon but this can be configured at any specific server instance.
    while get_more_notifications:
        get_notifications = masto.notifications(max_id=max_notification_id)

        # Remember the ID of the latest notification on first iteration
        if notification_count == 0:
            if len(get_notifications) > 0:
                latest_notification_id = get_notifications[0].id
            else:  # If there have not been any notifications yet, set value to "0"
                latest_notification_id = 0
                print(
                    "Nothing to do yet! Start interacting with your group account first."
                )
                get_more_notifications = False
        else:  # leave the while loop if there are no more notifications fetched
            if len(get_notifications) == 0:
                get_more_notifications = False

        # Initialize "last_seen_id" on first run. Notifications are ignored up
        # to this point, but newer ones will be considered subsequently.
        if my_config[group_name]["last_seen_id"] == "catch-up":
            my_config[group_name]["last_seen_id"] = str(latest_notification_id)
            config_store["write_NEW"] = True
            print(
                "Caught up to current timeline. Run again to start group-tooting."
            )

        for notification in get_notifications:
            max_notification_id = notification.id

            if (notification.id > int(my_config[group_name]["last_seen_id"])
                    and notification_count < max_notifications):
                my_notifications.append(notification)
            else:
                get_more_notifications = False
                break

            notification_count += 1

    # If there have been new notifications since the last run, update "last_seen_id"
    # and write config file to persist the new value.
    if latest_notification_id > int(my_config[group_name]["last_seen_id"]):
        my_config[group_name]["last_seen_id"] = str(latest_notification_id)
        config_store["write_NEW"] = True

    # Reverse list of notifications so that the oldest are processed first
    my_notifications = my_notifications[::-1]

    # run through the notifications and look for retoot candidates
    for notification in my_notifications:

        # Only from group members
        if notification.account.id in my_account["group_member_ids"]:

            # Is retooting of public mentions configured?
            if accept_retoots:
                if (notification.type == "mention"
                        and notification.status.visibility == "public"):
                    # Only if the mention was preceeded by either a "!" or a "*".
                    # To check for this, html tags have to be removed first.
                    repost_triggers = []
                    repost_triggers.append("!@" + my_account["username"])
                    repost_triggers.append("*@" + my_account["username"])
                    status = re.sub("<.*?>", "", notification.status.content)
                    if any(trigger in status for trigger in repost_triggers):
                        if not commandline_arguments["dry_run"]:
                            masto.status_reblog(notification.status.id)
                            print("Retooted from notification ID: " +
                                  str(notification.id))
                        else:
                            print(
                                "DRY RUN - would have retooted from notification ID: "
                                + str(notification.id))

            # Is reposting of direct messages configured? - if yes then:
            # Look for direct messages
            if accept_direct_messages:
                if (notification.type == "mention"
                        and notification.status.visibility == "direct"):
                    # Remove HTML tags from the status content but keep linebreaks
                    new_status = re.sub("<br />", "\n",
                                        notification.status.content)
                    new_status = re.sub("</p><p>", "\n\n", new_status)
                    new_status = re.sub("<.*?>", "", new_status)
                    # Get the group account's @username
                    account_username = "******" + my_account["username"]

                    # Only continue if the DM starts with the group account's @username
                    if new_status.startswith(account_username):
                        # Remove the group account's @username from the text
                        new_status = re.sub(account_username, "", new_status)
                        # "un-escape" HTML special characters
                        new_status = html.unescape(new_status)
                        if not commandline_arguments["dry_run"]:
                            # Repost as a new status
                            spoiler_text = notification.status.spoiler_text
                            # DMs from friendica always have a title that is used as spoiler_text.
                            # Remove it if it does not make sense.
                            if spoiler_text == "[no subject]":
                                spoiler_text = ""
                            masto.status_post(
                                new_status,
                                media_ids=media_toot_again(
                                    notification.status.media_attachments,
                                    masto),
                                sensitive=notification.status.sensitive,
                                visibility=dm_visibility,
                                spoiler_text=spoiler_text,
                            )
                            print(
                                "Newly posted from DM with notification ID: " +
                                str(notification.id))
                        else:
                            print(
                                "DRY RUN - would have newly posted from DM with notification ID: "
                                + str(notification.id))

                    # If the DM does not start with the group account's @username it will not
                    # trigger a new toot. Notify the originating user why this happened instead!
                    else:
                        if not commandline_arguments["dry_run"]:
                            new_status = (
                                "@" + notification.account.acct + "\n"
                                "Ohai! - This is a notification from your friendly tootgroup.py bot.\n\n"
                                "Your message has not been converted to a new group toot because it did "
                                "not start with @" + my_account["username"] +
                                "\n\n"
                                "Remember to put @" + my_account["username"] +
                                " at the very beginning if "
                                "you want to create a new group toot.")
                            masto.status_post(
                                new_status,
                                in_reply_to_id=notification.status.id,
                                visibility="direct",
                            )
                            print(
                                "Not posted from DM with notification ID: " +
                                str(notification.id),
                                end="",
                            )
                            print(". It did not start with @" +
                                  my_account["username"] + "!")
                        else:
                            print(
                                "DRY RUN - received DM with notification ID: "
                                + str(notification.id) +
                                ", but it did not begin with @" +
                                my_account["username"] + "!")

    # There have been changes requiring to persist the new configuration
    # but not in a dry-run condition
    if config_store["write_NEW"] and not commandline_arguments["dry_run"]:
        tootgroup_tools.configuration_management.write_configuration(
            config_store, my_config)

    print("Successful tootgroup.py run for " + "@" + my_account["username"] +
          " at " + my_config[group_name]["mastodon_instance"])
Ejemplo n.º 29
0
FilePointer=open('user.json','r')

#print(FilePointer)


Setting=json.load(FilePointer)
#print(Setting)
FilePointer.close()

# Register
# インスタンス毎に必要
mastodon.Mastodon.create_app(
    'global.rikou.don',
    api_base_url = Setting['url'],
    to_file = 'client_cred.txt'
)

# Login
# ユーザー毎のトークンも生成する
mstdn_handler=mastodon.Mastodon(
    client_id = 'client_cred.txt',
    api_base_url = Setting['url']
)

mstdn_handler.log_in(
    Setting['usermail'],
    Setting['password'],
    to_file = 'user_cred.txt'
)
Ejemplo n.º 30
0
 def __init__(self):
     self.bot = mastodon.Mastodon(access_token=settings.mastodon_key,
                                  api_base_url="https://botsin.space")