Skip to content

Instantly share code, notes, and snippets.

@gaxiiiiiiiiiiii
Created September 18, 2018 13:17
Show Gist options
  • Save gaxiiiiiiiiiiii/1a66f1b76ad62366a2b8f94365e9ac2f to your computer and use it in GitHub Desktop.
Save gaxiiiiiiiiiiii/1a66f1b76ad62366a2b8f94365e9ac2f to your computer and use it in GitHub Desktop.
import twitter
import os
from urllib.request import urlopen
from datetime import datetime
import twitter
import pandas as pd
import json
auth = twitter.OAuth(consumer_key = os.environ["COMSUMER_KEY"],
consumer_secret = os.environ["COMSUMER_SECRET"],
token = os.environ["TWITTER_TOKEN"],
token_secret = os.environ["TWITTER_SECRET"])
t = twitter.Twitter(auth=auth)
def get_new_articles():
# データ取得
article_api = "https://alis.to/api/articles/recent?limit=100&page=1"
raw_article_data = urlopen(article_api).read().decode("utf-8")
json_article_data = json.loads(raw_article_data)
articles_data = json_article_data["Items"]
df = pd.DataFrame(articles_data)
# timestamp => datetime
toDatetime = lambda x : datetime.fromtimestamp(int(x))
df["published_at"] = df["published_at"].map(toDatetime)
# 直近10分のデータのみ抽出
isNew = lambda x :( x - datetime.now()).seconds <= 600
isToday = lambda x : x.date() == datetime.now().date()
isNewMask = df["published_at"].map(isNew)
isTodayMask = df["published_at"].map(isToday)
result = df[isTodayMask & isNewMask]
return result
def get_newers(articles):
user_api = "https://alis.to/api/users/%s/articles/public?limit=100"
newers = []
for article in articles.iterrows():
# 著者の全記事データを取得
user = article[1]["user_id"]
raw_user_data = urlopen(user_api % user).read().decode("utf-8")
json_user_data = json.loads(raw_user_data)
user_articles = json_user_data["Items"]
if len(user_articles) == 1:
# 投稿数1の場合
article_id = user_articles[0]["article_id"]
user_name = get_user_name(user)
title = article[1]["title"]
url = f"https://alis.to/{user}/articles/{article_id}"
newer = {"title":title,"user":user_name,"url":url}
newers.append(newer)
return newers
def get_user_name(user_id):
user_api = "https://alis.to/api/users/%s/info"
raw_user_data = urlopen(user_api % user_id).read().decode("utf-8")
user_data = json.loads(raw_user_data)
name = user_data["user_display_name"]
return name
def create_texts(newers):
texts = []
for newer in newers:
text = "#ALISへようこそ\n\n"
text += newer["user"] + "さんの初投稿\n" + newer["title"] + "\n" + newer["url"]
texts.append(text)
return texts
if __name__ == "__main__":
articles = get_new_articles()
newers = get_newers(articles)
texts = create_texts(newers)
for text in texts:
t.statuses.update(status=text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment