4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ChatGPTとTwitter APIを組込んだPythonプログラムでXに自動ツイートする

Last updated at Posted at 2023-12-22

今回はXへの投稿をChatGPTにツイート文を書かせて自動投稿させるプログラムを開発してみます。
ChatGPTに対するプロンプトやパラメータを外部ファイルから取得したり、これをタスクスケジューラ等から自動実行したりすると便利ですが今回は割愛しています。

まずはTwitter APIをここから取得します。

APIキーには以下の5種類がありますので取得したら環境変数等に設定しておきましょう。
API Key
API Key Secret
Access Token
Access Token Secret
Bearer Token
【Sign up for Free Account】から取得して下さい。

1.ChatGPTにTweet文を書かせるコード

get_twitter.py

import openai
import os

# 環境変数からOpenai APIキーを取得する
openai.aip_key = os.environ["OPENAI_API_KEY"]

# ChatGPTによるツイート作成関数
def make_tweet():
    request = "私はAIを研究する企業を経営しています。私に代わってTwitterに投稿するツイートを150以内で作成して下さい。\n\nツイート作成の際は以下の文章を参考にして下さい。\n\n"

    tweet1 = "例文1:私ChatGPTは浦田さんに代わってPythonプログラムからツイートしています。"

    tweet2 = "例文2:私のfacebook'https://www.facebook.com/UrataSoft'もよろしくお願いします。"

    content = request + tweet1 + tweet2

    response = openai.chat.completions.create(
        
        model="gpt-3.5-turbo",
        temperature=0,
        messages=[
            {"role": "user", "content": content},
        ],
    )

    return response.choices[0].message.content

2.Xに接続しツイートさせるコード

bot_twitter.py

import tweepy
import os

# 環境変数からTwiiter APIキーを取得する
consumerKey = os.environ["TWITTER_CONSUMER_KEY"]
consumerSecret = os.environ["TWITTER_CONSUMER_SECRET"]
accessToken = os.environ["TWITTER_ACCESS_TOKEN"]
accessTokenSecret = os.environ["TWITTER_ACCESS_TOKEN_SECRET"]
bearerToken = os.environ["TWITTER_BEARER_TOKEN"]

# ツイート作成関数
def post(tweet):

    client = tweepy.Client(
        bearerToken,
        consumerKey,
        consumerSecret,
        accessToken,
        accessTokenSecret
    )

    client.create_tweet(text=tweet)

3.1と2の関数を呼び出し実際にツイートするコード

tweet.py

import gpt_twitter
import bot_twitter

tweet = gpt_twitter.make_tweet()
bot_twitter.post(tweet)

早速、この3のコードを実行してみます。
$ python tweet.py

以下の様にツイートされました。
image.png

4
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?