2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonとTkinterでTwitter投稿アプリを作る

Last updated at Posted at 2025-04-10

はじめに

Twitter APIを使ったシンプルな投稿アプリです。このアプリはPythonのGUIライブラリであるTkinterを使用して、入力した内容をTwitterに投稿するものです。windows11で無料でできます。

対象者

他人の投稿を見ずにtwitterの投稿だけをしたい方

結論

以下のコードを実行することで、Twitterへの投稿が可能な簡易アプリが完成します。

動作例

以下は実際に動作中のスクリーンショットです。

スクリーンショット 2025-04-11 020223.png
スクリーンショット 2025-04-11 024149.png
スクリーンショット 2025-04-11 023704.png

必要な準備

Twitter APIキー取得

Twitter APIの認証情報を取得し、コード内に設定する必要があります。Twitter Developer PortalでAPIキー(Consumer Key, Consumer Secret, Access Token, Access Secret)を取得してください。以下の記事に全部書いてあります。

参考: Twitter API認証情報の取得方法

Tweepyライブラリインストール

以下のコマンドでTweepyライブラリをインストールします。

pip install tweepy

Python環境準備

Python 3.xをインストール

実装コード

以下が実際のコードです。これをPython環境で実行すれば、GUIアプリケーションが起動します。

import tweepy
import tkinter as tk
from tkinter import messagebox

# 認証情報(Twitter Developer Portalで取得)
CONSUMER_KEY = "あなたのConsumer Key"
CONSUMER_SECRET = "あなたのConsumer Secret"
ACCESS_TOKEN = "あなたのAccess Token"
ACCESS_SECRET = "あなたのAccess Secret"

def post_tweet():
    """
    入力されたメッセージをツイートする関数
    """
    message = text_widget.get("1.0", tk.END).strip()  # テキストボックスから入力内容を取得

    if not message:
        messagebox.showwarning("警告", "ツイート内容が空です。入力してください。")
        return

    # Tweepy Clientを使用して認証
    client = tweepy.Client(
        consumer_key=CONSUMER_KEY,
        consumer_secret=CONSUMER_SECRET,
        access_token=ACCESS_TOKEN,
        access_token_secret=ACCESS_SECRET
    )

    try:
        # ツイート投稿(API v2)
        response = client.create_tweet(text=message)
        messagebox.showinfo("成功", f"ツイートが投稿されました!\nツイートID: {response.data['id']}")
        text_widget.delete("1.0", tk.END)  # 投稿後にテキストボックスをクリア
    except Exception as e:
        messagebox.showerror("エラー", f"ツイートの投稿中にエラーが発生しました: {e}")

def bind_shortcut(event):
    """
    Ctrl+Enterでpost_tweet関数を呼び出す
    """
    post_tweet()

# Tkinterウィンドウの設定
root = tk.Tk()
root.title("Twitter投稿アプリ")
root.geometry("400x300")

# ラベル
label = tk.Label(root, text="ツイート内容を入力してください:")
label.pack(pady=10)

# テキストボックス
text_widget = tk.Text(root, height=10, width=40)
text_widget.pack(pady=10)

# 投稿ボタン
tweet_button = tk.Button(root, text="ツイートする", command=post_tweet)
tweet_button.pack(pady=10)

# Ctrl+Enterキーのバインド
root.bind("<Control-Return>", bind_shortcut)

# メインループ
root.mainloop()

コードでやっていること

TkinterによるGUI構築

Tkinterでシンプルなウィンドウとテキスト入力欄、ボタンを作成しています。

Twitter API認証

Tweepyライブラリを使い、APIキーで認証しています。

ツイート投稿処理

client.create_tweet()メソッドで入力された内容をツイートしています。

もっとシンプルにするには

response = client.create_tweet(text=message)
messagebox.showinfo("成功", f"ツイートが投稿されました!\nツイートID: {response.data['id']}")

↑を↓にすれば投稿完了のメッセージボックスが出なくなります

client.create_tweet(text=message)

.exeにするには

必要なツールのインストール

Pythonスクリプトをアプリ化するには、PyInstallerというライブラリを使用します。以下のコマンドでインストールしてください。

pip install pyinstaller

実行可能ファイルの作成

以下のコマンドを実行して、Pythonスクリプトを実行可能ファイルに変換します。

pyinstaller --onefile --noconsole your_script_name.py

おわりに

Twitter API認証情報の取得は面倒ですが、ぜひ試してみてください。

追記(2025/04/21)

API制限がやけに早いと感じたので調べたところ、無料プランのAPI経由投稿数の上限が17件/1日になってたらしい。残念

2
2
1

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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?