ツイッターの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

タグ

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

Twitterの画像を抽出、非API

2018.11.07

Logging

Twitterの画像を抽出、非API
Goutteライブラリを使用してTwitterのメディアを抽出するだけで
APIを使用せずに17枚の画像が抽出することが可能。
これを改良してスクロールさせながらってのは出来ないのではないかな
特にVPSじゃないレンタルサーバーなどでは不可能じゃないのかと思います。

require_once './vendor/autoload.php';
use Goutte\Client;
$client = new Client();
$crawler = $client->request('GET','https://twitter.com/xxxx/media');
$img = $crawler->filter(".AdaptiveMedia-photoContainer.js-adaptive-photo img")->each(function ($node){
return $node->attr('src');
});

タグ

'src', 17, AdaptiveMedia-photoContainer, API, APITwitter, attr, autoload, Client, com, crawler, each, filter, function, GET, Goutte, gt, img, js-adaptive-photo, media', new, node, once, php, request, require, return, Twitter, use, vendor, VPS, xxxx, こと, これ, サーバー, スクロール, ない, メディア, ライブラリ, レンタル, 不可能, 使用, 出来, 可能, 思い, 抽出, 改良, , 特に, 画像, ,