x.comのAPI(FREE)にて自分のユーザー情報を取得するには

2024.06.05

Logging

おはようございます.x.comのAPI(FREE)にて自分のユーザー情報を取得するにはってググってもv1.1の情報だらけだったので情報を記載します.v2対応です.一部、有料でないと取得できない部分があり返却もエラーで返ってきますが、雛形コードを記載します.

注意事項
TwitterOAuthというComposerライブラリを使用しています.
APIなどの値はご自身のAPIに合わしてください.

参考にしたサイト
https://developer.x.com/en/docs/twitter-api/users/lookup/api-reference/get-users-me

<?php
date_default_timezone_set('Asia/Tokyo');
require_once "../vendor/autoload.php";

use Abraham\TwitterOAuth\TwitterOAuth;

class xMyProfile
{

    public $connection = null;
    public $response = null;

    public function __construct()
    {
        $this->connection = new TwitterOAuth(APIKEY, APISECRET, ACCESSTOKEN, ACCESSTOKENSECRET);
        $this->connection->setApiVersion("2");
        $this->response = $this->connection->get('users/me', [
            'expansions'=>'pinned_tweet_id',
            'tweet.fields'=>implode(',',[
                'attachments',
                'author_id',
                'context_annotations',
                'conversation_id',
                'created_at',
                'edit_controls',
                'entities',
                'geo',
                'id',
                'in_reply_to_user_id',
                'lang',
                'non_public_metrics',
                'public_metrics',
                'organic_metrics',
                'promoted_metrics',
                'possibly_sensitive',
                'referenced_tweets',
                'reply_settings',
                'source',
                'text',
                'withheld'
            ]),
            'user.fields' => implode(',', [
                'created_at',
                'description',
                'entities',
                'id',
                'location',
                'most_recent_tweet_id',
                'name',
                'pinned_tweet_id',
                'profile_image_url',
                'protected',
                'public_metrics',
                'url',
                'username',
                'verified',
                'verified_type',
                'withheld'
            ])
        ]);
        return $this;
    }

    /**
     * プロフィール情報全てを取得
     */
    public function getMyProfile()
    {
        return $this->response;
    }
    /**
     * プロフィールアイコンURLを取得
     */
    public function getIconUrl()
    {
        return $this->response->data->profile_image_url;
    }
}
var_dump((new xMyProfile)->getMyProfile());
//print (new xMyProfile)->getIconUrl();

この記事はQiitaに掲載していた記事になります.

明日へ続く.

著者名  @taoka_toshiaki

Profile
高知県在住の@taoka_toshiakiです、記事を読んで頂きありがとうございます.
数十年前から息を吸うように日々記事を書いてます.たまに休んだりする日もありますがほぼ毎日投稿を心掛けています😅.
SNSも使っています、フォロー、いいね、シェア宜しくお願い致します🙇.
SNS::@taoka_toshiaki

タグ

connection, construct, edit_controls, getIconUrl, getMyProfile, implode, lt, null, organic_metrics, print, promoted_metrics, public, qiita, quot, response, return, use AbrahamTwitterOAuthTwitterOAuth, users, vendor, X.com,

Photo by Pixabay on Pexels.com

#久しぶりのコード`Xにポストするコード`

2023.11.17

Logging

おはよう御座います、さて正月休みは11日ぐらいあります、いやー正月休みはネトフリとゲームざんまいしてみたいと思っているのですが、結局どこかに出ていったりとかして目標達成できずにズルズルと休みを過ごすことになりそうです。👈前と言っていることが違いますね🙇。

さて、久しぶりにコードを書きました、この記事だけ見るとプログラマーじゃないかって思われるので最初に記載しときます。毎日のように仕事ではコードを書いています、仕事以外でコードを書いたのは一週間ぶりかなぁ。でも、このコードはポストでも書いている通り、特に難しいコードでもないのでオープンに公開しました。

このコードには必要ないコードが紛れているのはこのコードが使いましたコードだからです😂。

<?php
date_default_timezone_set('Asia/Tokyo');
ini_set("display_errors", 0);
require_once "../tw-config-v2.php";
require_once "../vendor/autoload.php";

use Abraham\TwitterOAuth\TwitterOAuth;

class merukari{
    public $connection = null;
    public $pdo = null;

    public function __construct()
    {
        $this->connection = new TwitterOAuth(APIKEY, APISECRET,ACCESSTOKEN,ACCESSTOKENSECRET);
        $this->connection->setApiVersion("2");
    }

    public function tweet($pattern)
    {
        $result = $this->connection->post("tweets", ["text" =>$pattern], true);
    }
    
    public static function pattern()
    {
        $pattern = [
            'メルカリで参考書を取り扱ってます📖 どれも綺麗な状態です。#学び #python Cシャープ #プログラム ⏭ https://jp.mercari.com/user/profile/808093563',
            'メルカリで参考書を出品してます📖 どれも綺麗な状態です。#学び #機械学習 #AI #プログラム ⏭ https://jp.mercari.com/user/profile/808093563',
            'メルカリで参考書を売ってます📖 どれも綺麗な状態です。#学び #人工知能 #python #プログラム ⏭ https://jp.mercari.com/user/profile/808093563',
            'メルカリで参考書を取り扱ってますよ📖 どれも綺麗な状態です。#学び #テック #企業 #学び #プログラム ⏭ https://jp.mercari.com/user/profile/808093563',
        ];

        return $pattern[ (int)rand(0,(count($pattern)-1))];
    }
}

try {
    if($argv[1] === 'merukari'){
        (new merukari())->tweet(merukari::pattern());
    }
} catch (\Throwable $th) {
    //throw $th;
}

もしかしたら、以前にもコードを公開して2回目になっていたりするかも知れません。そうだったらごめんなさい、無駄に記事を量産しています(反省。

そうそうXのハッシュタグ廃止は誤解だそうです。思い出したので書いときます、、、。

明日へ続く。

著者名  @taoka_toshiaki

Profile
高知県在住の@taoka_toshiakiです、記事を読んで頂きありがとうございます.
数十年前から息を吸うように日々記事を書いてます.たまに休んだりする日もありますがほぼ毎日投稿を心掛けています😅.
SNSも使っています、フォロー、いいね、シェア宜しくお願い致します🙇.
SNS::@taoka_toshiaki

タグ

argv, Asia, catch, connection, construct, int, lt, null, pattern, Python, quot, rand, return, throw, Throwable, true, try, Tweet, use AbrahamTwitterOAuthTwitterOAuth, vendor,

Twitter API V2では画像ツイートが出来ないと流れてきたので対処方法

2023.06.02

Logging

おはようございます。先日、Twitter API V2では画像ツイートが出来ないと流れてきたので対処方法を載せときます。Qiitaにも掲載していますが、こちらでも記載します。コードはいつまで使用出来るかは不明ですね、イーロン・マスクのサジカゲンで無料プランでは出来なくなる可能性を秘めています。今のところ、使用できるコードです。PHP8系では動きますがPHP7系は:mixedの部分を退けてあげないと動かないかもです。因みにPythonのサンプルコードが公式にはあったような気がします。

<?php

require_once "tw-config-v2.php";
require_once "vendor/autoload.php";

use Abraham\TwitterOAuth\TwitterOAuth;

class tw
{
    public $connection = null;
    public $media = null;
    public function __construct()
    {
        $this->connection = new TwitterOAuth(APIKEY, APISECRET, ACCESSTOKEN, ACCESSTOKENSECRET);
    }

    /**
     * イメージのエンドポイントを取得する v1.1 そのうち廃止されそう。
     * @param $imageName
     * @return boolean
     */
    public function getImage($imageName = null): bool
    {
        if (empty($imageName)) {
            return false;
        }
        $this->media = $this->connection->upload('media/upload', ['media' => "/var/www/html/tw/tmp/images/$imageName"]);
        return true;
    }

    /**
     * イメージ付きでツイート。
     * @param $text
     * @return mixed
     */
    public function tweet($text = null): mixed
    {
        if (!empty($text) && isset($this->media->media_id_string)) {
            $param = [
                'text' => $text,
                'media' => [
                    'media_ids' => [
                        $this->media->media_id_string
                    ]
                ]
            ];
            $this->connection->setApiVersion('2');
            return $this->connection->post('tweets', $param, true);
        }
        return false;
    }
}

if($argv[0]){
    $tw = new tw();
    if($tw->getImage("php2023.png"))
    {
        $tw->tweet("これはテストです");
    }    
}

著者名  @taoka_toshiaki

Profile
高知県在住の@taoka_toshiakiです、記事を読んで頂きありがとうございます.
数十年前から息を吸うように日々記事を書いてます.たまに休んだりする日もありますがほぼ毎日投稿を心掛けています😅.
SNSも使っています、フォロー、いいね、シェア宜しくお願い致します🙇.
SNS::@taoka_toshiaki

タグ

argv, bool, connection, construct, empty, getImage, isset, media', mixed, PARAM, qiita, quot, quot;vendor, return, tmp, tw, Tweet, use AbrahamTwitterOAuthTwitterOAuth, イーロン, サジカゲン,

ツイッターのDM内容をOpenAI api(chatGPT)で判別しスパムの場合ブロックする。#ソースコード

2023.04.17

Logging

おはようございます、スパムをブロックするソースコードを掲載します。ご自由にご使用いただけばと思っています。これを作ったのは先週の日曜日のことです、TwitterのDMに悩まされていたので何か方法はないかなって思って作ったのがこれです。実際、自分は試しに導入してみたのですが、精度はまずまず良い結果でした。因みに自分は作ったのですが今のところ、使ったのは先週の日曜日だけで未だに手動でブロックしています。使わない理由は大量のスパムが来ているわけではないので、特に問題は無いからです。唯、大量のスパムが来ている人にはそれなりにお役に立てるツールかも知れないです。

ツイッターのDM内容をOpenAI api(chatGPT)で判別しスパムの場合ブロックする。

スパム精度は結構良いです。

使用方法

  • コマンドで実行
php BlockMessage.php spamcheck

使用したComposerのライブラリ

  • TwitterOAuth
  • openai-php/client

phpのバージョン

  • php8.1

前提条件

  • 掲載していないファイルは推測して作ってください。
<?php
require_once "../vendor/autoload.php";
require_once "../tw-config-v2.php";
require_once "../openAI-config.php";

use Abraham\TwitterOAuth\TwitterOAuth;

class BlockMessage
{
    var $connection = null;

    public function __construct()
    {
        $this->twitterConnection();
        $result = $this->getTwitterDM();
        if(!$this->judgmentSpam($result[0])){
            $this->setTwitterBlockedUser($result[1]);
        }
    }

    public function twitterConnection()
    {
        // TwitterOAuthクラスのインスタンスを作成する
        $this->connection = new TwitterOAuth(APIKEY, APISECRET, ACCESSTOKEN, ACCESSTOKENSECRET);
        // APIバージョンを設定する
        $this->connection->setApiVersion('2');
    }

    /**
     * DMを取得する
     * @return array 
     */
    public function getTwitterDM()
    {
        $dm_events = $this->connection->get('dm_events',["expansions"=>"sender_id","user.fields"=>"username,id"]);
        return [$dm_events->data[0]->text,$dm_events->data[0]->sender_id,$dm_events->data[0]->id];
    }
    /**
     * OpenAI APIを使用してスパム判定
     * @param string $text
     * @return false
     */
    public function judgmentSpam(string $text="")
    {
        if (!$text) return false;
        $client = OpenAI::client(OPENAIAPIKEY);
        $result = $client->chat()->create([
            'model' => 'gpt-3.5-turbo',
            'messages' => [
                ["role"=>"system", "content"=>'Your job is to identify spam, please determine if the message is spam or not. If it is spam, please write "This is spam". For non-spam messages, write "OK".'],
                ["role"=>"system", "content"=>'respond to in English.'],
                ['role'=> 'user', 'content' => $text],
            ]
        ]);
        if(preg_match("/(OK)/i",$result->choices[0]->message->content)){
            print "non-spam".PHP_EOL;
            return true;    
        }
        if(preg_match("/(spam)/i",$result->choices[0]->message->content)){
            print "This is spam".PHP_EOL;
            return false;
        }
        return true;
    }

    /**
     * スパムアカウントをブロック
     * @param string $blocked_user_id
     * @return false
     */
    public function setTwitterBlockedUser(string $blocked_user_id = "")
    {
        if (!$blocked_user_id) return false;

        $block_result = $this->connection->post('users/'.MYTWID.'/blocking', ['target_user_id' => $blocked_user_id], true);
        if ($block_result->data->blocking) {
            print 'Blocked user successfully.'.PHP_EOL;
            return true;
        } else {
            print 'Failed to block user.'.PHP_EOL;
            return false;
        }
    }
}
if($argv[1]==="spamcheck"){
    new BlockMessage();
}

https://github.com/taoka-toshiaki/BlockMessage

著者名  @taoka_toshiaki

Profile
高知県在住の@taoka_toshiakiです、記事を読んで頂きありがとうございます.
数十年前から息を吸うように日々記事を書いてます.たまに休んだりする日もありますがほぼ毎日投稿を心掛けています😅.
SNSも使っています、フォロー、いいね、シェア宜しくお願い致します🙇.
SNS::@taoka_toshiaki

タグ

argv, chat, ChatGPT, choices, Client, Composer, connection, construct, getTwitterDM, messages, OPENAIAPIKEY, print, quot, spam, spamcheck, string, Twitter, twitterConnection, TwitterOAuth, vendor,

Photo by Pixabay on Pexels.com

Twitter-API-v2ツイート数珠繋ぎ #コード公開 #php

2022.10.04

Logging

おはようございます。土日祝も関係なくブログは毎日書いています🤮。

さて、今日はPHP言語でTwitterAPIバージョン2(v2)を使用してツイート数珠繋ぎをする方法を抜粋して記載していきます。こういうコードは今のところ出回っていないようです。少し調べれば公式サイトに記載しているのだけども・・・。まだ、日本語に対応した記事が少ないようです。v2でツイートする方法やリツイートする方法は何故かあるのだけどリプライ(Reply)[/statuses/update]する方法が記事としては記載していなかったので?記載します。

<?php
require_once "vendor/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;

class tw{
    var $connection = null;
    function __construct()
    {
        $this->connection = new TwitterOAuth(APIKEY, APISECRET,ACCESSTOKEN, ACCESSTOKENSECRET);
        $this->connection->setApiVersion("2");
    }

    function pickup_tweets(mixed $tw_text=null){
         $obj = (object)[];
        if(isset($tw_text) && is_array($tw_text)){
            foreach ($tw_text as $key => $value) {
                if(preg_replace("/[ | ]/","",$value)){
                    $obj = !$key?(
                        $this->connection->post("tweets", ["text" =>$value], true)
                    ):
                    (
                        $this->connection->post("tweets", ["reply"=>["in_reply_to_tweet_id"=>$obj->data->id],"text"=> $value], true)
                    );
                }
            }
            return true;
        }
        return false;
    }
}

最初に結論とコードのアルゴリズムに付いて解説します。まず、tweetsのパラメーターでリプライ出来るように変更されています。v1.1とはそこが変わっているので同じ仕組みを検索しがちですがそれでは検索にヒットしないようです🤔。まずはエンドポイントの変更点の確認が必要みたい👏。

エンドポイントのv1.1からv2への対応表

エンドポイントのv1.1からv2への対応表が公式から出ているので確認してみてください↑。

次にコードの解説ですがまずTwitterOAuthライブラリをインストールを行い、defineなどの設定なども考慮した上で実行してみてください(コードに追記記載が必要)。変数、$tw_textは配列です。また投稿する文字が入っていると考えてください。そしてこのコードを下記のような考え方で実行してみてください。

<?php
       require_once "tw-index.php";
       $tw_text[0] ="test1";
       $tw_text[1] ="test2";
       $tw = new tw();
       if($tw->pickup_tweets($tw_text)){
        $ret["msg"] = "ok";
       }else{
        $ret["msg"] = "NG";
       }
       var_dump($ret);

※前提条件としてtwitter社にAPIの申請を行って受理されている事。

Twitter API v2 ツイート数珠繋ぎ

これで思った通り実行出来たと思います。尚、自分のように管理画面などを作って数珠繋ぎの投稿するのも良いかも知れません🫠。

著者名  @taoka_toshiaki

Profile
高知県在住の@taoka_toshiakiです、記事を読んで頂きありがとうございます.
数十年前から息を吸うように日々記事を書いてます.たまに休んだりする日もありますがほぼ毎日投稿を心掛けています😅.
SNSも使っています、フォロー、いいね、シェア宜しくお願い致します🙇.
SNS::@taoka_toshiaki

タグ

2, Abraham, autoload, class, connection, function, lt, null, once, php, quot, Reply, require, statuses, tw, Twitter-API-v, TwitterAPI, TwitterOAuth, UPDATE, use, var, vendor, コード, サイト, ツイート, ところ, バージョン, ブログ, リツイート, リプライ, , 今日, 使用, 公式, 公開, 土日, 対応, 少し, 抜粋, 数珠繋ぎ, 方法, 日本語, 毎日, , 言語, 記事, 記載,

数珠繋ぎにTweet(リプライ)するPHP言語のコードは意外にも簡単。

2021.08.28

Logging

先日、高知県はコロナ感染症が111人になったそうです。早くコロナワクチン接種?2回目を打ちたいです、ただファイザー社のワクチンなのでデルタ株のウィルスは軽症化させるだけで無症状や感染しないようにはならないという事です。それでも重症化を防げるので打たないより打った方が良いですね?。なお、混合ワクチン接種が結構無敵だとか?インドではDNAワクチン接種を世界初で承認したみたいですね。新たな変異種も防ぐことが出来れば一気にDNAワクチン接種が世界的に進みそうです。

さて、前置きはここまでとして、数珠繋ぎにTweet(リプライ)するPHP言語のコードは意外にも簡単に書けました、なお、TwitterOAuthというライブラリを使用して呟いています。

作った経緯は数珠繋ぎにする方法などは調べてもヒットしなかったので記載しようと思ったわけです。今回の方法でアファリエイトなどを紹介などや長文のツイートが行えるなどいろいろな用途に使えるかと思います。

※このソースコードはコマンドライン(CUI)から叩かないと(実行)、動かない仕様になっています。

<?php
require_once("../vendor/autoload.php");
use Abraham\TwitterOAuth\TwitterOAuth;
if ($argv[0]) {
    require_once "./tw-config.php";
    $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
    date_default_timezone_set('Asia/Tokyo');
    $affiliate = json_decode(file_get_contents("./affiliate.json"));
    $id = null;
    foreach ($affiliate->{date("w")} as $key=>$val) {
        $str = $id?array("status"=>$affiliate->{date("w")}[$key]->txt,"in_reply_to_status_id"=>$id):array("status"=>$affiliate->{date("w")}[$key]->txt);
        $res = $connection->post("statuses/update",$str);
        $id = $res->id;
    }
}
{
    "0": [
        {
            "txt": ""
        },
        {
            "txt": "2"
        },
        {
            "txt": "3"
        }
    ],
    "1": [
        {
            "txt": "1"
        },
        {
            "txt": "2"
        },
        {
            "txt": "3"
        }
    ],
    "2": [
        {
            "txt": "1"
        },
        {
            "txt": "2"
        },
        {
            "txt": "3"
        }
    ],
    "3": [
        {
            "txt": "1"
        },
        {
            "txt": "2"
        },
        {
            "txt": "3"
        }
    ],
    "4": [
        {
            "txt": "1"
        },
        {
            "txt": "2"
        },
        {
            "txt": "3"
        }
    ],
    "5": [
        {
            "txt": "1"
        },
        {
            "txt": "2"
        },
        {
            "txt": "3"
        }
    ],
    "6": [
        {
            "txt": "1"
        },
        {
            "txt": "2"
        },
        {
            "txt": "3"
        }
    ]
}

著者名  @taoka_toshiaki

Profile
高知県在住の@taoka_toshiakiです、記事を読んで頂きありがとうございます.
数十年前から息を吸うように日々記事を書いてます.たまに休んだりする日もありますがほぼ毎日投稿を心掛けています😅.
SNSも使っています、フォロー、いいね、シェア宜しくお願い致します🙇.
SNS::@taoka_toshiaki

タグ

$affiliate, argv, Asia, connection, CUI, date, foreach, gt, json_decode, lt, null, php require_once, quot, TwitterOAuth, txt, use AbrahamTwitterOAuthTwitterOAuth, val, vendor, アファリエイト, コマンドライン,

あるキーワードをライクするTwitter API。

2019.11.06

Logging

さくらレンタルサーバー、もともとmecab(メカブ)が入っているらしい。
自動であるキーワードに対してライクする方法(Twitter API)です。
たぶん、こんなコードはなかったと思います、
過去記事「ワードプレス過去記事のツイートをボット化する方法。」と併用してお使いください。
そうでないと動きませんので…。
知り合いエンジニアさんとかに組み込んでもらってください。

<?php
function mecab_tw_like($txt="",$connection=Null){
    if(!$txt)return false;
    if(!is_object($connection))return false;
    $cmd = "echo "$txt" | mecab";
    exec($cmd, $opt, $return_ver);
    //var_dump($opt);
    foreach($opt as $key=>$val){
        $r = explode("t",$val);
        if(preg_match("/名詞/",$r[1])){
            $statuses = $connection->get(
                'search/tweets',
                array(
                    'q'                 => $r[0],
                    'count'             => '3',
                    'lang'              => 'ja',
                    'locale'            => 'ja',
                    'result_type'       => 'recent',
                    'include_entities'  => 'false'
                )
            );
            if(is_array($statuses->statuses) and $statuses->statuses){
                foreach( $statuses->statuses as $tweet ){
                    $id = $tweet->id;
                    $result = $connection->post(
                        'favorites/create',
                        array(
                            'id' => $id
                        )
                    );
                }
            }
        }
    }
}

著者名  @taoka_toshiaki

Profile
高知県在住の@taoka_toshiakiです、記事を読んで頂きありがとうございます.
数十年前から息を吸うように日々記事を書いてます.たまに休んだりする日もありますがほぼ毎日投稿を心掛けています😅.
SNSも使っています、フォロー、いいね、シェア宜しくお願い致します🙇.
SNS::@taoka_toshiaki

タグ

API, cmd, connection, echo, exec, false, function, if, is, like, lt, Mecab, null, object, opt, php, quot, return, tw, Twitter, txt, ver, エンジニア, キーワード, コード, サーバー, さくら, ツイート, プレス, ボット, メカブ, ライク, レンタル, ワード, 併用, 方法, 自動, 記事, 過去,