이제 hexo 블로그에 스팀잇 모든 글을 가져와 보자.

in SCT.암호화폐.Crypto6 years ago (edited)

안녕하세요.

굳헬로 @goodhello 입니다.

어제는 안피곤 @anpigon 님께서 만든 Hexo Steem 프로젝트를 이용해서 스팀잇에 올린 글을 가져와서 마크다운 형식인 md 파일로 저장하여 hexo 블로그에 나오도록 해보았는데요.

그런데 스팀잇 글을 100개 밖에 가지고 오지 않아 한번 연구를 해보았습니다.

먼저 안피곤님의 Hexo Steem 모듈은

xeho 블로그 내에 node_modules 에 저장이 되어 있는데요.

거기에 들어 있는 index.js 파일을 한번 열어보겠습니다.

var steem = require('steem');

function updateSteemArticles(username) {
  steem.api.getDiscussionsByBlog({limit:100, tag:username}, function(err, result) {
    for (var i = 0; i < result.length; i++) {
      const { title, body, category, author, permlink, created, json_metadata } = result[i];
      if (result[i].author == username || hexo.config.steem_resteems) {
        const tags = JSON.parse(json_metadata).tags || [];
        const date = new Date(`${created}Z`);
        const content = body.replace(/\|/g, '|').replace(/%/g, '%').replace(/{/g, '{').replace(/}/g, '}');
        // let t = title.replace(/"(.*)"/g, '“$1”').replace(/"/g, '“');//.replace(/\[|\]|:|-|#|\(|\)|\'/g, '').replace('?', '').replace('?', '');
        // console.log(t, tags);
        hexo.post.create({
          slug: `${category}/${author}/${permlink}`,
          title: title.replace(/"(.*)"/g, '“$1”').replace(/"/g, '“'),
          content,
          date,
          tags,
          author,
        }, true)
      }
    }
  });
}

if (hexo.config.steem_users) {
  for (var i = 0; i < hexo.config.steem_users.length; i++) {
    updateSteemArticles(hexo.config.steem_users[i])
  }
} else {
  console.log('No steem usernames found, please add to the _config.yml')
}

대충 살펴보니 steem api의 getDiscussionsByBlog()를 이용해서 username에 해당하는 블로그를 100개 가져와서 hexo 포스트로 생성을 하는 코드인 것 같습니다.

그럼 steem api의 getDiscussionsByBlog()를 잘 이용하면 스팀잇의 모든 글을 가져올 수 있을 것 같은데요.

단순히 limit 를 수정해서는 100개 이상 가져와 지지는 않더군요. 100개 보다 작게 설정하면 작동하는데 100개 이상은 안되더군요. 아마도 가져올 수 있는 max 수치를 100개로 정해 둔 것 같습니다.

그래서 열심히 검색을 해보았습니다. 역시 검색을 하니 다 나오는군요.

steem.api.getDiscussionsByBlog(query, function(err, result) {
  console.log(err, result);
});

steem.api.getDiscussionsByBlog()를 이용할때 query 값을

var query = {
  "tag": username,
  "limit": 100,
  "start_author": username,
  "start_permlink": "permlink" }

위와 같이 설정하여 username에 대한 start_permlink를 지정해주면 해당 포스트부터 지난 포스트 100개를 불러올 수 있더라구요.

@codingman 님께서 올려주신Steem.js으로 자신의 블로그 post 정보 응용 글에 설명이 잘 되어 있어서 쉽게 이해가 되더군요.

위 글에 있는 코드를 참고하여 hexo-steemindex.js 파일을 다음과 같이 수정하였습니다.

var steem = require('steem');
var cnt=0;
var query = {
  "tag": "",
  "limit": 100
};

function updateSteemArticles(username) {  
  query.tag= username;
  steem.api.getDiscussionsByBlog(query, function(err, result) {
    for (var i = 0; i < result.length-1; i++) {
      const { title, body, category, author, permlink, created, json_metadata } = result[i];
      if (result[i].author == username || hexo.config.steem_resteems) {
        const tags = JSON.parse(json_metadata).tags || [];
        const date = new Date(`${created}Z`);
        const content = body.replace(/\|/g, '|').replace(/%/g, '%').replace(/{/g, '{').replace(/}/g, '}');
        let t = title.replace(/"(.*)"/g, '“$1”').replace(/"/g, '“');//.replace(/\[|\]|:|-|#|\(|\)|\'/g, '').replace('?', '').replace('?', '');
        console.log(t, tags);
        hexo.post.create({
          slug: `${category}/${author}/${permlink}`,
          title: title.replace(/"(.*)"/g, '“$1”').replace(/"/g, '“'),
          content,
          date,
          tags,
          author,
        }, true)
      }
    }
    cnt=result.length;
    if(cnt<100){
      const { title, body, category, author, permlink, created, json_metadata } = result[cnt-1];
      if (result[cnt-1].author == username || hexo.config.steem_resteems) {
        const tags = JSON.parse(json_metadata).tags || [];
        const date = new Date(`${created}Z`);
        const content = body.replace(/\|/g, '|').replace(/%/g, '%').replace(/{/g, '{').replace(/}/g, '}');
        let t = title.replace(/"(.*)"/g, '“$1”').replace(/"/g, '“');//.replace(/\[|\]|:|-|#|\(|\)|\'/g, '').replace('?', '').replace('?', '');
        console.log(t, tags);
        hexo.post.create({
          slug: `${category}/${author}/${permlink}`,
          title: title.replace(/"(.*)"/g, '“$1”').replace(/"/g, '“'),
          content,
          date,
          tags,
          author,
        }, true)
      }   
      return;
    }
    else{
      query.start_author= result[cnt-1].author; 
      query.start_permlink= result[cnt-1].permlink;
      console.log(query);

      updateSteemArticles(username); 
    }
  });
}

if (hexo.config.steem_users) {
  for (var i = 0; i < hexo.config.steem_users.length; i++) {
    updateSteemArticles(hexo.config.steem_users[i])
  }
} else {
  console.log('No steem usernames found, please add to the _config.yml')
}

steem.api.getDiscussionsByBlog() 를 실행하는 updateSteemArticles() 함수를 한번 실행하고 난 후 포스트 값이 100개 이하가 될 때까지 마지막 포스트를 start_permlink 로 지정해서 자기 자신을 계속 호출하도록 코드를 만들어 보았습니다.

이제 hexo 서버를 실행하면!!!!!

저의 모든 블로그 내역을 가져오게 되는데....

이제까지 스팀잇에 올린 글이 무려 1000개가 넘는군요.

그리고 hexo 블로그내에 source/_posts폴더를 보면 제가 이제까지 올린 모든 스팀잇 포스트가 md 파일로 저장되어 있습니다. xeho 블로그에서 생성한 2개를 제외하면 1174개!!!!

그런데 xeho 블로그를 가동할때마다 hexo-steem이 실행되어 또 모든 스팀잇 글을 가져와서 md 파일로 생성하고 있는데, 이부분은 한번만 동작시키고, 이 후는 최근 글 몇개만 가져오던지 하는 방법으로 고쳐야 할 것 같네요.

그럼 오늘은 여기까지!!!!

다음 시간에는 블로그를 더욱 멋지게 꾸미기 위하여 테마를 한번 적용해 볼까 합니다. 그리고 태그가 어마어마하게 많은데.. 그것도 손을 좀 봐야 할 것 같네요.

그리고 서버 없는 분들을 위해 gitgub에 배포하는 것도 해봐야 하고... 도메인 연결도 해야하고... 앞으로도 할일이 계속 생길 것 같습니다.

열심히 파이팅해야겠어요~

그럼 여러분들도 오늘 하루 파이팅 하시길 바라며, 이번 한주도 행복하세요~

Sort:  

크으 굳헬로님 역쉬 짱이십니다! 멋져용!!!

ㅎㅎ 감사합니다~

다른분들이 너무 좋은 걸 이미 만들어 주셨기 때문에 쉽게 따라할 수 있었던 것 같습니다.

뭘 자꾸 이상한걸 하고 그러세요? ㅋㅋㅋㅋ

ㅎㅎㅎㅎㅎㅎ 이상하면 치과에.... 가봐야겠군요~~ ㅋㅋㅋㅋ

Congratulations @goodhello! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You published a post every day of the week

You can view your badges on your Steem Board and compare to others on the Steem Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

To support your work, I also upvoted your post!

Do not miss the last post from @steemitboard:

Downvote challenge - Add up to 3 funny badges to your board
Use your witness votes and get the Community Badge
Vote for @Steemitboard as a witness to get one more award and increased upvotes!

윽....이건 또 뭐죠?

ㅎㅎㅎㅎ 새로운 걸 공부중이에요~

Hi @goodhello!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your UA account score is currently 3.540 which ranks you at #4344 across all Steem accounts.
Your rank has improved 241 places in the last three days (old rank 4585).

In our last Algorithmic Curation Round, consisting of 79 contributions, your post is ranked at #20.

Evaluation of your UA score:
  • You're on the right track, try to gather more followers.
  • The readers like your work!
  • Try to work on user engagement: the more people that interact with you via the comments, the higher your UA score!

Feel free to join our @steem-ua Discord server

According to the Bible, The Story of Gideon: On Making Choices and the Second Coming.

Watch the Video below to know the Answer...

(Sorry for sending this comment. We are not looking for our self profit, our intentions is to preach the words of God in any means possible.)


Comment what you understand of our Youtube Video to receive our full votes. We have 30,000 #SteemPower. It's our little way to Thank you, our beloved friend.
Check our Discord Chat
Join our Official Community: https://steemit.com/created/hive-182074

My name is Jesus Christ and I do not condone this spamming in my name. Your spam is really fucking annoying @hiroyamagishi aka @overall-servant aka @olaf123 and your spam-bot army. You spam everybody, we ask you to stop, you refuse to, we downvote you, you downvote us. This is not what my father, God, created the universe for. You must stop spamming immediately or I will make sure that you go to hell.

If anybody wants to support my eternal battling of these relentless religion spammers, please consider upvoting this comment or delegating to @the-real-jesus

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.082
BTC 60785.45
ETH 1557.47
USDT 1.00
SBD 0.47