示例#1
0
def createAccount(username, isNsfw, subreddit):
    mastodon = Mastodon(client_id=settings.MASTODON['CLIENT_ID'],
                        client_secret=settings.MASTODON['CLIENT_SECRET'],
                        api_base_url=settings.MASTODON['BASE_URL'])
    email = "r_{}_bot@{}".format(username.lower(),
                                 settings.MASTODON['EMAIL_DOMAIN']),
    account = Account(username=username,
                      email=email,
                      password=settings.MASTODON['DEFAULT_PASSWORD'],
                      subreddit=subreddit)
    account.save()
    try:
        mastodon.create_account(account.username,
                                account.password,
                                account.email,
                                agreement=True,
                                locale='en',
                                scopes=['read', 'write'],
                                to_file=path.join(
                                    "tokens",
                                    "{}.token".format(account.username)))
        baseUrl = settings.MASTODON['BASE_URL'].replace("https://",
                                                        "").replace(
                                                            "http://", "")
        postBody = "@{}@{} is now available to follow!".format(
            account.username, baseUrl)
        postToMainAccount(postBody, isNsfw)
        mastodon = Mastodon(client_id=settings.MASTODON['CLIENT_ID'],
                            client_secret=settings.MASTODON['CLIENT_SECRET'],
                            api_base_url=settings.MASTODON['BASE_URL'])
        mastodon.account_follow(account.username)
    except Exception as e:
        # Check if user already exists with the default password
        sessionHandle = _getMastodonHandle(account)
        statuses = sessionHandle.account_statuses(
            sessionHandle.account_verify_credentials()['id'], limit=1)
        if len(statuses) > 0:
            status = statuses[0]
            for post in subreddit.post_set.all().order_by('created'):
                if post.reddit_url in status.content:
                    account.lastInserted = post.id
                    account.save()
                    break

    return account
示例#2
0
                    new_user_list.append(toot['account']['id'])
                    f.write("Toot:%s\n" % json.dumps(toot))
                if len(toot['mentions']) > 0:
                    for mention in toot['mentions']:
                        if '@' in mention['acct']:
                            mention_domain=mention['acct'].split('@')[1]
                        else:
                            mention_domain=INSTANCE
                        if mention['acct'] not in BLACKLIST['users'] and mention_domain not in BLACKLIST['instances'] and not '#nobot' in toot['account']['note'] and not '#<span>nobot</span>' in toot['account']['note']:
                            new_user_list.append(mention['id'])
                            f.write("Mention:%s\n" % json.dumps(mention))
            #except:
            #    print('Error while trying to do something with %s' % (toot))
            runparams['since_id'] = toot['id']

for user_id in new_user_list:
    if user_id not in my_followed_list or user_id not in runparams['list_seen']:
        if DEBUG:
            print('Trying to follow %i' % user_id)
        new_followed+=1
        mastodon.account_follow(user_id)
        my_followed_list.append(user_id)
        runparams['list_seen'].append(user_id)

if TOOT and new_followed > 0 and runparams['runcount'] > 10:
    mastodon.status_post('I am now following %i users out of the %i I have seen, boost some toots from others so I can see them :)' % (total_followed+new_followed,len(runparams['list_seen'])),visibility='unlisted')
    runparams['runcount'] = 1

with open('.Autofollow.state.json','w') as file:
        json.dump(runparams,file)
示例#3
0
文件: app.py 项目: Mitame/followbot
class App():
    def __init__(self):
        self.mastodon = Mastodon(
            api_base_url=os.environ["BASE_URL"],
            client_id=os.environ["OAUTH_CLIENT_ID"],
            client_secret=os.environ["OAUTH_CLIENT_SECRET"],
            access_token=os.environ["OAUTH_ACCESS_TOKEN"],
        )

    def run(self):
        self.ws = WebSocketApp(
            self.mastodon.api_base_url.replace("https", "wss").replace("http", "ws") \
             + "/api/v1/streaming/" + "?access_token=%s&stream=public" % self.mastodon.access_token,
            on_error = self.on_error,
            on_message = self.on_message,
            on_close = self.on_close
        )

        self.ws.run_forever()

    def follow(self, account):
        try:
            if account["locked"] or "#dnf" in account["note"].lower():
                logging.info("Account %s is locked or has #dnf in their note" %
                             account["acct"])
                return
        except KeyError:
            pass

        user = user_table.find_one({"uid": account["id"]})
        if user:
            logging.info("Already following or told not to follow %s" %
                         account["acct"])
            return

        self.mastodon.account_follow(account["id"])
        logging.info("Now following %s" % account["acct"])

        user_table.insert({
            "acct": account["acct"],
            "uid": account["id"],
            "following": True
        })

    def on_error(self, ws, error):
        pass
        # print(error)

    def on_message(self, ws, message):
        event_data = json.loads(message)
        payload_data = json.loads(event_data["payload"])

        # print("Event: %s" % event_data["event"])
        # pprint(payload_data)

        if event_data["event"] == "update":
            self.follow(payload_data["account"])

            for account in payload_data["mentions"]:
                # Get all the account info
                accts = self.mastodon.account_search(account["acct"])
                if len(accts) == 0:
                    self.follow(account)
                else:
                    self.follow(accts[0])

    def on_close(self, ws):
        print("WS CLOSED")