Skip to content

Instantly share code, notes, and snippets.

@vim13
Last active July 16, 2018 11:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vim13/ef4da22e19fb5b54fc98b2783487dfb3 to your computer and use it in GitHub Desktop.
Save vim13/ef4da22e19fb5b54fc98b2783487dfb3 to your computer and use it in GitHub Desktop.
自分の全toot取得後tweet
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import re
import os
import time
import ast
import tweepy
import requests
from mastodon import Mastodon
def fileOpen(path):
opened_file = open(path, 'r')
text = opened_file.read()
opened_file.close()
return text
def login():
mastodon = Mastodon(client_id = '/home/ubuntu/python/app_key.txt', access_token = '/home/ubuntu/python/user_key.txt', api_base_url = 'https://mstdn.jp')
return mastodon
def twitterAuth(path):
dic = fileOpen(path)
keys = ast.literal_eval(dic)
auth = tweepy.OAuthHandler(keys['consumer_key'], keys['consumer_secret'])
auth.set_access_token(keys['access_token'], keys['access_token_secret'])
api = tweepy.API(auth)
return api
def makeTweet(toot_list):
api = twitterAuth('/home/ubuntu/python/twitter_keys.txt')
toot_list.reverse()
for tweet in toot_list:
media_ids = []
for filename in tweet['media']:
temp = '/home/ubuntu/python/temp.jpg'
name = filename['url']
request = requests.get( name, stream=True)
if request.status_code == 200:
with open(temp, 'wb') as image:
for chunk in request:
image.write(chunk)
res = api.media_upload(temp)
os.remove(temp)
media_ids.append(str(res.media_id))
if tweet['toot']:
api.update_status(status = tweet['toot'][0][:140].encode('utf-8'), media_ids = media_ids)
else:
api.update_status(media_ids = media_ids)
time.sleep(10)
def ngWord(x):
lists = fileOpen('/home/ubuntu/python/NGWords.txt').decode('utf-8')
comp = re.compile(lists, re.I)
i = 0
while i >= 0:
m = comp.search(x, i)
if m:
num = m.end() - m.start()
rep = u"*" * num
x = x[:m.start()] + rep + x[m.end():]
i = m.start() + 1
else:
break
return x
def makeList(mastodon):
toot_list = []
user_dict = mastodon.account_verify_credentials()
since_id = 100344593028894782 - 1
max_id = 200344593028894782
while max_id > since_id:
toot = mastodon.account_statuses(user_dict['id'], max_id = max_id, since_id = since_id, limit=20)
if toot:
max_id = toot[-1][u'id'] - 1
for line in toot:
toot_dict = { u'toot':[], u'media':[]}
if line[u'media_attachments']:
toot_dict['media'] = line[u'media_attachments']
if line[u'content']:
x =line[u'content']
p = re.compile(r"<[^>]*?>")
x = p.sub("", x)
x = ngWord(x)
toot_dict['toot'].append(x)
toot_list.append(toot_dict)
else:
max_id = 0
makeTweet(toot_list)
def main():
mastodon = login()
makeList(mastodon)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment