def mstdn_name_update(status):
    mastodon = Mastodon(access_token="key/username-updater-usercred.secret",
                        api_base_url="https://mstdn.maud.io")
    with open(PATH + "/mstdn-id.txt", "r") as f:
        id = int(f.read())
    display_name = mastodon.account(id)["display_name"][:-2]
    mastodon.account_update_credentials(display_name=display_name + status)
示例#2
0
def check_toots(config, options, retry_count=0):
    """
    The main function, uses the Mastodon API to check all toots in the user timeline, and delete any that do not meet any of the exclusion criteria from the config file.
    """
    try:
        if not options.quiet:
            print(
                "Fetching account details for @",
                config["username"],
                "@",
                config["base_url"],
                sep="",
            )

        if options.pace:
            mastodon = Mastodon(
                access_token=config["access_token"],
                api_base_url="https://" + config["base_url"],
                ratelimit_method="pace",
            )
        else:
            mastodon = Mastodon(
                access_token=config["access_token"],
                api_base_url="https://" + config["base_url"],
                ratelimit_method="wait",
            )

        user_id = mastodon.account_verify_credentials(
        ).id  # verify user and get ID
        account = mastodon.account(user_id)  # get the account
        timeline = mastodon.account_statuses(user_id,
                                             limit=40)  # initial batch

        if not options.quiet:
            print("Checking", str(account.statuses_count), "toots")

        # check first batch
        # check_batch() then recursively keeps looping until all toots have been checked
        check_batch(config, options, mastodon, user_id, timeline)

    except KeyboardInterrupt:
        print("Operation aborted.")

    except KeyError as val:
        print("\n⚠️  error with in your config.yaml file!")
        print("Please ensure there is a value for " + str(val) + "\n")

    except MastodonAPIError as e:
        if e.args[1] == 401:
            print(
                "\n🙅  User and/or access token does not exist or has been deleted (401)\n"
            )
        elif e.args[1] == 404:
            print("\n🔭  Can't find that server (404)\n")
        else:
            print("\n😕  Server has returned an error (5xx)\n")

        if options.verbose:
            print(e, "\n")

    except MastodonNetworkError as e:
        if retry_count == 0:
            print(
                "\n📡  ephemetoot cannot connect to the server - are you online?"
            )
            if options.verbose:
                print(e)
        if retry_count < 4:
            print("Waiting " + str(options.retry_mins) +
                  " minutes before trying again")
            time.sleep(60 * options.retry_mins)
            retry_count += 1
            print("Attempt " + str(retry_count + 1))
            check_toots(config, options, retry_count)
        else:
            print("Gave up waiting for network\n")

    except Exception as e:
        if options.verbose:
            print("ERROR:", e)
        else:
            print("ERROR:", str(e.args[0]), "\n")
示例#3
0
j = int(allIds)
t = 0

while j != 10000000 and t != 300:
    accounts = []
    followers = []
    following = []
    error = []
    #print j
    if j % 100 == 0:
        consolidate('accounts')
        consolidate('followers')
        consolidate('following')

    try:
        account = mastodon.account(j)
        accounts.append(account)
        with open(pathTo + 'accounts/accounts' + str(j) + '.json',
                  'w') as accountsFile:
            json.dump(account, accountsFile, default=datetimeconvert)

        if account['url'][:len(url)] == url:
            if len(account) > 0:
                if account["followers_count"] > 0:
                    followersTemp = getLists(mastodon.account_followers(j))
                    if account["followers_count"] != len(followersTemp[1]):
                        error.append(['followers', j])
                    followers.append(followersTemp)

                if account["following_count"] > 0:
                    followingTemp = getLists(mastodon.account_following(j))
示例#4
0
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'
username = '******'

mastodon = Mastodon(client_id=cid_file,
                    access_token=token_file,
                    api_base_url=url)

# 対象アカウントのユーザーIDを取得する。
user_list = mastodon.account_search(username, limit=1)
user_id = user_list[0]['id']

# 対象アカウントのフォロー数を表示する。
user_dict = mastodon.account(user_id)
print(user_dict['following_count'])
示例#5
0
        pass
#mastodon.notifications_clear()
#print(notification_id_pool)
#print(notification_pool[-1])
#
#print(last_update_time)
#print(stupidDateToEpoch(notification_pool[-1]["created_at"]))
#print(time.time())
#
#sys.exit()

while True:
#	try:
        reply_to_mentions(get_mentions(my_id, last_notification))
        if(time.localtime()[6]==4): # if it's friday
            if(last_ff==0) or (last_ff-time.time())>(60*60*2):
                last_ff=time.time()
                samplesize=6
                if(len(followers)<samplesize):
                    samplesize=len(followers)
                chosen_followers=random.sample(followers, samplesize)
                msg=["#ff #followfriday"]
                for f in chosen_followers:
                    msg.append("@"+mastodon.account(f)["acct"])
                mastodon.toot(" \n".join(msg))
        time.sleep(600)
#	except Exception as e:
#            print(e)
#	    pass

示例#6
0
class MastodonInterface(SingleCommandInterface):
    log = logging.getLogger(__name__)
    user_manager: UserManager
    data: CovidData
    viz: Visualization
    mastodon: Mastodon

    INFECTIONS_UID = "infections"
    VACCINATIONS_UID = "vaccinations"
    ICU_UID = "icu"

    def __init__(self, access_token: str, mastodon_url: str, user_manager: UserManager, covid_data: CovidData,
                 visualization: Visualization, no_write: bool = False):
        super().__init__(user_manager, covid_data, visualization, 5, no_write)
        self.mastodon = Mastodon(access_token=access_token, api_base_url=mastodon_url)
        self.update_follower_number()

    def update_follower_number(self):
        info = self.mastodon.account(323011)
        number = info['followers_count']
        self.user_manager.set_platform_user_number(number)

    def upload_media(self, filename: str) -> str:
        upload_resp = self.mastodon.media_post(filename, mime_type="image/jpeg")
        if not upload_resp:
            raise ValueError(f"Could not upload media to Mastodon. API response {upload_resp.status_code}: "
                             f"{upload_resp.text}")

        return upload_resp['id']

    def write_message(self, messages: List[BotResponse], reply_obj: Optional[object] = None) -> bool:
        for message in messages:
            media_ids = []
            if message.images:
                for file in message.images:
                    media_ids.append(self.upload_media(file))
            try:
                with API_RESPONSE_TIME.labels(platform='mastodon').time():
                    if not reply_obj:
                        response = self.mastodon.status_post(message.message, media_ids=media_ids, language="deu",
                                                             visibility="unlisted")
                    else:
                        response = self.mastodon.status_reply(reply_obj, message.message, media_ids=media_ids,
                                                              language="deu", )
                self.update_metrics()
                if response:
                    self.log.info(f"Toot sent successfully {len(message.message)} chars)")
                    SENT_MESSAGE_COUNT.inc()
                    reply_obj = response
                else:
                    raise ValueError(f"Could not send toot!")
            except MastodonAPIError as api_error:
                self.log.error(f"Got error on API access: {api_error}", exc_info=api_error)
                raise api_error
        return True

    def update_metrics(self):
        if self.mastodon.ratelimit_limit:
            API_RATE_LIMIT.labels(platform='mastodon', type='limit').set(self.mastodon.ratelimit_limit)

        if self.mastodon.ratelimit_remaining:
            API_RATE_LIMIT.labels(platform='mastodon', type='remaining').set(self.mastodon.ratelimit_remaining)

    def get_mentions(self) -> Iterable[SingleArgumentRequest]:
        with API_RESPONSE_TIME.labels(platform='mastodon').time():
            notifications = self.mastodon.notifications(
                exclude_types=['follow', 'favourite', 'reblog' 'poll', 'follow_request'])
        self.update_metrics()
        mentions = []
        bot_name = "@D64_Covidbot"
        for n in notifications:
            if n['type'] != "mention":
                continue
            text = general_tag_pattern.sub("", n['status']['content'])
            mention_pos = text.lower().find(bot_name.lower())
            text = text[mention_pos + len(bot_name):]
            if text:
                created = n['status']['created_at']
                mentions.append(SingleArgumentRequest(n['status']['id'], text, n['status'], created))
        return mentions