[PYTHON] [Life hack] Women's Anna support bot with Twitter API

スクリーンショット 2020-01-02 0.21.30.png

TL;DR Create a bot that supports Joshiana (retweets photos and videos). Use TwitterAPI and Google App Script (GAS). I think you can be happy if you follow this account ^^

Introduction

On New Year's Day, when I was messing around, I found a beautiful woman named Mako Tamura when I was watching the news. I wanted to follow Twitter, but I didn't have an official or bot, so I decided to make it myself.

About language selection. My main language is Python, but I want it to be executed regularly and arbitrarily. This time I decided to write in GAS.

Premise

――I will only talk about what I did (I hope you enjoy the concept) --Detailed tasks are left to the articles introduced

What i did

  1. Apply for Twitter API
  2. GAS and Twitter integration
  3. Write a GAS to post on Twitter
  4. Specify a trigger to execute automatically

For 1, refer to this article 2 refers to this article (overwhelming thanks) At this stage, if something is appropriate, I think that you can Tweet from GAS.

3 I will write nicely from here For now

//Creation of an instance for authentication
var twitter = TwitterWebService.getInstance(
  'xxxx',//API Key
  'xxxx'//API secret key
);

//Link authentication of apps
function authorize() {
  twitter.authorize();
}

//Deauthorize
function reset() {
  twitter.reset();
}

//Callback after authentication
function authCallback(request) {
  return twitter.authCallback(request);
}

//Retweet
function retweet(tweetid){
  var service  = twitter.getService();
  var response = service.fetch('https://api.twitter.com/1.1/statuses/retweet/'+tweetid+'.json', {
                               method: 'post',
                               payload: { id: tweetid}
                               });
  Logger.log(JSON.parse(response));
}

//Post
function doPost(){
  var id = 'xxx';
  retweet(id);
}

It looks like this. On the premise that 1.2. Is completed If you specify the appropriate Tweetid (as you can see from the URL of the posted tweet screen) in the'xxx'of the doPost function and execute the doPost function, it should be retweeted wonderfully.

Let's make it possible to fetch this id part automatically. It looks like the following.


//Check if the tweet is within 24 hours [Newly added function]
function within24(twt){
  var oneday = 1000 * 60 * 60 * 24
  var created = twt.created_at;
  var c = new Date(created);
  var today = new Date();
  var timeDelta = (today.getTime() - c.getTime())/oneday;
  Logger.log(timeDelta);
  if (timeDelta<1){
    return true;
  }else{
    return false;}
}

//Get a search word,Returns an array of tweet ids that match the conditions [Newly added function]
function search(word){
  if (word == "") {
    return;
  }
  
  word = encodeURIComponent(word);
  
  var url, options, response, jsonString, json, tweets = [];

  //Twitter Search API URL
  var API_URL = "https://api.twitter.com/1.1/search/tweets.json?";
  
  try {
    
    url = API_URL + "count=100" + "&q=" + word;
    
    try {
      var service  = twitter.getService();
      var response = service.fetch(url, {method: 'get'});
      var array = JSON.parse(response)['statuses'];
      var leng = array.length;
      var output = [];
      //Check if the image exists
      for(var i=0; i<leng; i++){
        var twt = array[i];
        var ent = twt.entities;
        if ('media' in ent){
          if (within24(twt)){
            output.push(twt['id_str']);
          }
        }
      }
    } catch(e) {
      Logger.log(e);
      return;
    }
    return output;
  } catch(e){
    Logger.log(e);
  }
}

//Post [Function that was a little tampered with earlier]
//Specify a search word and throw it to the search function, then throw the resulting array to the retweet function and execute
function doPost(){
  var nums = search('Mako Tamura');
  if (nums){
    nums.forEach(function(id){
      retweet(id);});
  }
}

I wrote the explanation of each function in the commented out part!

4 At this point, just specify the trigger! Go to the trigger management screen with "Edit"-> "Trigger of current project" Select Add Trigger. スクリーンショット 2020-01-02 3.53.29.png The condition is saved in this way so that the doPost function is executed once a day.

So, I don't really know who the text is for, so I will supplement the missing parts in the future.

reference

GAS×TwitterBot search API (Official)

Recommended Posts

[Life hack] Women's Anna support bot with Twitter API
Support yourself with Twitter API
Use Twitter API with Python
Successful update_with_media with twitter API
I made a Twitter Bot with Go x Qiita API x Lambda
Create a Twitter BOT service with GAE / P + Tweepy + RIOT API! (Part 1)
Create a Twitter BOT service with GAE / P + Tweepy + RIOT API! (Part 2)
Collecting information from Twitter with Python (Twitter API)
Post from another account with Twitter API
Live a typingless Twitter life with Alexa
Extract sudden buzzwords with twitter streaming API
Let's make a Twitter Bot with Python!
Tweet regularly with the Go language Twitter API
Make a Twitter trend bot with heroku + Python
LINE BOT with Python + AWS Lambda + API Gateway
Steps to create a Twitter bot with python