HiÐΞClassic

Google Colaboratory でグラフを作成しツイートをする

SHOGAKU
2 years ago
事前準備Twitter Developerアカウントelevated設定アプリケーション権限これまでに作成した記事の延長で今回は臨みますIC NFTトランザクションデータをグラフにするデータをグラフで確認グラフを添付してツイートする

Google Colaboratory でグラフを作成し、ツイートをする

Google Colaboratory → https://colab.research.google.com/?hl=ja#

自分用の備忘録なので雑です。すいません


事前準備

Twitter Developerアカウント

Twitter APIの認証情報(consumer_key、consumer_secret、access_token、access_token_secret)を取得するには、Twitter Developerアカウントを作成し、Twitterアプリを作成する必要があります。手順は次のとおりです。

  1. https://developer.twitter.com にアクセスして、Twitter Developerアカウント(まだ持っていない場合)を作成します。

  2. Twitterアプリを作成する手順:

  • 左側のナビゲーションメニューから「Apps」メニューアイテムをクリックします。
  • 「Create an app」ボタンをクリックします。
  • 「Create an App」フォームの必須フィールドに記入します。
  • Developer AgreementとPrivacy Policyを読んで受け入れます。
  • 「Create」ボタンをクリックします。
  1. アプリを作成したら、「Keys and Tokens」タブに移動してAPIキーとトークンを生成します:
  • 「Consumer Key」と「Consumer Secret」のセクションの「Generate」ボタンをクリックしてこれらのキーを生成します。
  • 「Access Token & Access Token Secret」のセクションの「Generate」ボタンをクリックしてこれらのトークンを生成します。
  1. この認証情報はTwitterアカウントへのアクセスを許可するため、安全に保管する必要があります。誰にも共有しないでください。

注:API認証情報はいつでも取り消されたり再生成される可能性があります。認証情報に問題がある場合は、再生成する必要があるかもしれません。


elevated設定

elevated設定が必要です。以下が参考になりました。

私の場合は1日程度かかりました。申請して1回質問が来て回答して完了。という感じ


アプリケーション権限

権限が「Read Only」となっている為、「Read and Write」もしくは「Read, Write and Access direct messages」に変更する必要がある。

Twitter Developerアカウントでのアクセス許可の設定は以下の手順で行います。

  1. Twitter Developerアカウントにログインします。
  2. Apps セクションに移動します。
  3. 生成したアプリケーションを選択します。
  4. [Permissions]タブを選択します。
  5. [Read and Write]または [Read, Write, and Access Direct Messages]のいずれかを選択します。
  6. [Update settings]ボタンをクリックして変更を保存します。

これで、Twitter APIを使用するアプリケーションにアクセス許可を与えることができます。


これまでに作成した記事の延長で今回は臨みます


IC NFTトランザクションデータをグラフにする

前回記事の内容を参考にIC NFTデータを抽出

!rm -r nfts_data
!git clone https://github.com/lukasvozda/nfts_data.git
!pip install -r nfts_data/requirements.txt

from ic.agent import *
from ic.identity import *
from ic.client import *
from ic.candid import Types, encode, decode

# Inicialisation
client = Client(url = "https://ic0.app")
iden = Identity()
agent= Agent(iden, client)

# Endpoint that we want to pull data from
function_to_call = 'transactions'

# List of NFTs canisters we want to pull data from
# You can find it on Entrepot clicking on NFTs 
canisters = [
    {
        'name': 'Motoko',
        'id': 'oeee4-qaaaa-aaaak-qaaeq-cai'
    },
    {
        'name': 'BTC Flowers',
        'id': 'pk6rk-6aaaa-aaaae-qaazq-cai'
    },
    {
        'name': 'Poked bots',
        'id': 'bzsui-sqaaa-aaaah-qce2a-cai'
    },
]

# File to write results to
f  = open('result.txt','w')
# Header row
f.write(f"collection,index,token,icp,time_updated,timestamp,seller,buyer")

for c in canisters:
    params = []

    params = encode(params)

    response = agent.query_raw(c["id"], function_to_call, params)

    print("Getting collection:", c["name"])

    trans = response[0]["value"]
    for i,t in enumerate(trans):
        price = str(t['_3364572809']/100000000)
        timestamp = t['_1291635725']
        token = t['_338395897']
        seller = t['_1782082687']
        buyer = t['_3136747827']
        f.write(f"\n{c['name']},{i},{token},{price},,{timestamp},{seller},{buyer}")

f.close()

データをグラフで確認

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns


df = pd.read_csv("result.txt", header=0)
df['timestamp'] = pd.to_datetime(df['timestamp'])

sns.scatterplot(x='timestamp', y='icp', hue='collection', legend=True, data=df)
plt.grid(linestyle='dotted')

#レジェンド
plt.legend(loc='top right')

#X軸のラベルを変更
import matplotlib.dates as mdates

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%y/%m'))
plt.gca().xaxis.set_major_locator(mdates.MonthLocator())
plt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=2))
plt.gcf().autofmt_xdate()

#Y軸 Max1000
import matplotlib.pyplot as plt

plt.ylim(0, 1000)

plt.show()


グラフを添付してツイートする

import tweepy
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

df = pd.read_csv("result.txt", header=0)
df['timestamp'] = pd.to_datetime(df['timestamp'])

sns.scatterplot(x='timestamp', y='icp', hue='collection', legend=True, data=df)
plt.grid(linestyle='dotted')

#レジェンド
plt.legend(loc='top right')

#Y軸 Max1000
import matplotlib.pyplot as plt
plt.ylim(0, 1000)

#X軸のラベルを変更
import matplotlib.dates as mdates

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%y/%m'))
plt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=2))
plt.gcf().autofmt_xdate()

plt.savefig('plot.png')


# Twitter認証情報は環境変数から取得
auth = tweepy.OAuthHandler(os.environ["TWITTER_CONSUMER_KEY"], os.environ["TWITTER_CONSUMER_SECRET"])
auth.set_access_token(os.environ["TWITTER_ACCESS_TOKEN"], os.environ["TWITTER_ACCESS_SECRET"])


# APIオブジェクトを作成
api = tweepy.API(auth)

# ツイート内容
api.update_with_media('plot.png', status='test tweet #ICP_NFT_transaction')

環境変数に以下の値を設定してください。

  • TWITTER_CONSUMER_KEY
  • TWITTER_CONSUMER_SECRET
  • TWITTER_ACCESS_TOKEN
  • TWITTER_ACCESS_SECRET

結果、以下のようなツイートなりました。

https://twitter.com/ussu_ussu_ussu/status/1620735799003168772


コメント
いいね
投げ銭
最新順
人気順
SHOGAKU
2 years ago
コメント
いいね
投げ銭
最新順
人気順
トピック
アプリ

Astar Network

DFINITY / ICP

NFT

DAO

DeFi

L2

メタバース

BCG

仮想通貨 / クリプト

ブロックチェーン別

プロジェクト

目次
Tweet
ログイン