Last active
May 8, 2024 12:32
-
-
Save ueponx/589a5e6c1694c0af2e45b8bbf4401a91 to your computer and use it in GitHub Desktop.
XにポストするQRコードを作成
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import urllib.parse | |
import qrcode | |
# ライブラリインストール | |
# pip install qrcode[pil] | |
# 実行方法 | |
# python x_qr_code_generator.py "#Python プログラミング" "https://example.com" "output.png" | |
def generate_twitter_url(text, url=None): | |
"""指定されたテキストとオプショナルなURLからTwitter投稿用のURLを生成する""" | |
text_encoded = urllib.parse.quote(text) | |
if url: | |
url_encoded = urllib.parse.quote(url) | |
return f"http://twitter.com/intent/tweet?text={text_encoded}&url={url_encoded}" | |
else: | |
return f"http://twitter.com/intent/tweet?text={text_encoded}" | |
def create_qr_code(url, filename): | |
"""指定されたURLからQRコードを生成し、ファイルに保存する""" | |
qr = qrcode.QRCode( | |
version=1, | |
error_correction=qrcode.constants.ERROR_CORRECT_L, | |
box_size=10, | |
border=4, | |
) | |
qr.add_data(url) | |
qr.make(fit=True) | |
img = qr.make_image(fill_color="black", back_color="white") | |
img.save(filename) | |
print(f"QRコードを '{filename}' に保存しました。") | |
def main(): | |
parser = argparse.ArgumentParser(description='Twitter投稿用のリンクを作成し、QRコードを生成します。') | |
parser.add_argument('text', type=str, help='ツイートに含めるテキスト') | |
parser.add_argument('url', type=str, nargs='?', default=None, help='ツイートに含めるURL(オプショナル)') | |
parser.add_argument('filename', type=str, help='生成されるQRコードの画像ファイル名') | |
args = parser.parse_args() | |
twitter_url = generate_twitter_url(args.text, args.url) | |
create_qr_code(twitter_url, args.filename) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment