From f4dd7e87037074d1bc8b6f7c979a13ff02a0da95 Mon Sep 17 00:00:00 2001 From: "Kaz Saita(raspi4)" Date: Tue, 12 Mar 2024 20:15:36 +0900 Subject: [PATCH] confirm working --- .gitignore | 4 +- .vscode/settings.json | 5 + README.md | 1 + capture_bot_san/__main__.py | 119 +++++++++++++++++- .../{config.py => config_reader.py} | 2 + capture_bot_san/{token.py => token_reader.py} | 14 ++- poetry.lock | 30 ++++- pyproject.toml | 1 + 8 files changed, 164 insertions(+), 12 deletions(-) create mode 100644 .vscode/settings.json rename capture_bot_san/{config.py => config_reader.py} (96%) rename capture_bot_san/{token.py => token_reader.py} (83%) diff --git a/.gitignore b/.gitignore index 31d2eef..09e9745 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ .venv/* .env config.yaml -__pycache__/ \ No newline at end of file +__pycache__/ +*.md +!READEME.md \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..3d48a45 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,5 @@ +{ + "terminal.integrated.enablePersistentSessions": true, + "python.terminal.activateEnvInCurrentTerminal": true, + "python.defaultInterpreterPath": "${workspaceFolder}/.venv/bin/python" +} \ No newline at end of file diff --git a/README.md b/README.md index e69de29..fc6aa48 100644 --- a/README.md +++ b/README.md @@ -0,0 +1 @@ +# Capture Bot San diff --git a/capture_bot_san/__main__.py b/capture_bot_san/__main__.py index dfc0fdb..a6ba2c2 100755 --- a/capture_bot_san/__main__.py +++ b/capture_bot_san/__main__.py @@ -1,13 +1,122 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +import discord +import dropbox +import pytz +import datetime +import os +from posixpath import normpath +from tzlocal import get_localzone +from zoneinfo import ZoneInfo -from . import token -from . import config +from . import token_reader +from . import config_reader -def main(): - config.read_config() - token.read_tokens() +config = config_reader.read_config() +tokens = token_reader.read_tokens() +discordClient = discord.Client(intents=discord.Intents.all()) +dbx = dropbox.Dropbox( + app_key=tokens.DROPBOX_APP_KEY, + app_secret=tokens.DROPBOX_APP_SECRET, + oauth2_refresh_token=tokens.DROPBOX_REFRESH_TOKEN) +def get_timestamp(): + timezone = get_localzone() + here = ZoneInfo(str(timezone)) + timestamp = datetime.datetime.now(here).strftime('%Y%m%d%H%M%S') + return timestamp + +@discordClient.event +async def on_ready(): + print("Discord Client Logged in as {} (id {}) ...".format(discordClient.user.name, discordClient.user.id)) + print("Waiting for message..") + +@discordClient.event +async def on_message(message): + timestamp = get_timestamp() + print('Incoming Message: timestamp {}'.format(timestamp)) + output_string = '# ' + timestamp + '\n' #1st level header + + channel = '#' + message.channel.name # channel -> tag + output_string += channel + "\n\n" + + # text content + output_string += message.content + "\n\n" + + # attached media image/video + num_attachments = len(message.attachments) + + if num_attachments > 0: + for index, attachment in enumerate(message.attachments): + + # image/video + if attachment.content_type.startswith('image'): + file_name = 'image{}_{}.png'.format(timestamp, index) + elif attachment.content_type.startswith('video'): + file_name = 'video{}_{}.mp4'.format(timestamp, index) + else: + continue # not supported + + + image_data = await attachment.read() + + + # create temporal file + try: + with open(file_name, 'wb') as f: + f.write(image_data) + except Exception as e: + print('Error:', e) + exit(1) + + # upload + dropbox_path = normpath(config.DROPBOX_MEDIA_FOLDER) + '/' + file_name + dbx.files_upload(open(file_name, 'rb').read(), + dropbox_path, + mode=dropbox.files.WriteMode.overwrite) + os.remove(file_name) + output_string += '![[' + file_name + ']]\n' + + # download markdown file to append + tmp_markdown_file = './' + config.MARKDOWN_FILENAME + markdown_file = normpath(config.DROPBOX_TEXTFILE_FOLDER) + '/' + config.MARKDOWN_FILENAME + + try: + dbx.files_download_to_file(tmp_markdown_file, markdown_file) + except Exception as e: + print('Error:', e) + exit(1) + + orig_text = '' + try: + with open(tmp_markdown_file, encoding='utf-8') as f: + orig_text = f.read() + except Exception as e: + print('Error:', e) + exit(1) + + new_text = output_string + orig_text + + try: + with open(tmp_markdown_file, 'w', encoding='utf-8') as f: + f.write(new_text) + except Exception as e: + print('Error:', e) + exit(1) + + # upload + try: + dbx.files_upload(open(tmp_markdown_file, 'rb').read(), + markdown_file, + mode=dropbox.files.WriteMode.overwrite) + except Exception as e: + print('Error:', e) + exit(1) + + +def main(): + print("Connecting to discord...") + discordClient.run(tokens.DISCORD_TOKEN) if __name__ == '__main__': main() diff --git a/capture_bot_san/config.py b/capture_bot_san/config_reader.py similarity index 96% rename from capture_bot_san/config.py rename to capture_bot_san/config_reader.py index 0aab96d..71eb04a 100755 --- a/capture_bot_san/config.py +++ b/capture_bot_san/config_reader.py @@ -47,6 +47,8 @@ def read_config(): print('Config file not found. Creating...') create_config() read_config() + + return config diff --git a/capture_bot_san/token.py b/capture_bot_san/token_reader.py similarity index 83% rename from capture_bot_san/token.py rename to capture_bot_san/token_reader.py index d5dcc40..f462da1 100755 --- a/capture_bot_san/token.py +++ b/capture_bot_san/token_reader.py @@ -1,6 +1,7 @@ import dotenv dotenv.load_dotenv() import os +import dropbox from dropbox import DropboxOAuth2FlowNoRedirect from . import constants @@ -27,7 +28,7 @@ def read_tokens(): write_back = True print('Discord token not set') print('Go to https://discord.com/developers/applications/ and create it.') - print('New Application -> Bot -> Token -> Copy!') + print('New Application -> Bot -> Token-> Copy! or Reset Token if you have already created it.') token.DISCORD_TOKEN = input('Discord Token: ').strip() if token.DROPBOX_APP_KEY == '' or token.DROPBOX_APP_SECRET == '': write_back = True @@ -39,21 +40,24 @@ def read_tokens(): token.DROPBOX_APP_SECRET = input('App secret: ').strip() if token.DROPBOX_REFRESH_TOKEN == '': write_back = True - print('Dropbox refresh token not set. Try to get it...') + print('Dropbox refresh token is not set. Try to get it...') if token.DROPBOX_APP_KEY == '' or token.DROPBOX_APP_SECRET == '': print('Requries Dropbox app key and secret. Give up.') exit(1) - auth_flow = DropboxOAuth2FlowNoRedirect(token.DROPBOX_APP_KEY, consumer_secret=token.DROPBOX_APP_SECRET, use_pkce=False, token_access_type='offline') + auth_flow = DropboxOAuth2FlowNoRedirect(token.DROPBOX_APP_KEY, consumer_secret=token.DROPBOX_APP_SECRET, use_pkce=False, token_access_type='offline') authorize_url = auth_flow.start() print('1. Go to:', authorize_url) print('2. Click "Allow" (you might have to log in first)') print('3. Copy the authorization code.') auth_code = input('Enter the authorization code here: ').strip() try: - oauth_result = auth_flow.finish(auth_code) + oauth_result = auth_flow.finish(auth_code) print("Refresh token:", oauth_result.refresh_token) - token.DROPBOX_REFRESH_TOKEN = oauth_result.refresh_token + token.DROPBOX_REFRESH_TOKEN = oauth_result.refresh_token + with dropbox.Dropbox(app_key=token.DROPBOX_APP_KEY, app_secret=token.DROPBOX_APP_SECRET, oauth2_refresh_token=token.DROPBOX_REFRESH_TOKEN) as dbx: + dbx.users_get_current_account() + print("Refresh token test Successful") except Exception as e: print('Error:', e) exit(1) diff --git a/poetry.lock b/poetry.lock index 1a9bebc..b888457 100644 --- a/poetry.lock +++ b/poetry.lock @@ -629,6 +629,34 @@ files = [ ply = ">=3.4" six = ">=1.12.0" +[[package]] +name = "tzdata" +version = "2024.1" +description = "Provider of IANA time zone data" +optional = false +python-versions = ">=2" +files = [ + {file = "tzdata-2024.1-py2.py3-none-any.whl", hash = "sha256:9068bc196136463f5245e51efda838afa15aaeca9903f49050dfa2679db4d252"}, + {file = "tzdata-2024.1.tar.gz", hash = "sha256:2674120f8d891909751c38abcdfd386ac0a5a1127954fbc332af6b5ceae07efd"}, +] + +[[package]] +name = "tzlocal" +version = "5.2" +description = "tzinfo object for the local timezone" +optional = false +python-versions = ">=3.8" +files = [ + {file = "tzlocal-5.2-py3-none-any.whl", hash = "sha256:49816ef2fe65ea8ac19d19aa7a1ae0551c834303d5014c6d5a62e4cbda8047b8"}, + {file = "tzlocal-5.2.tar.gz", hash = "sha256:8d399205578f1a9342816409cc1e46a93ebd5755e39ea2d85334bea911bf0e6e"}, +] + +[package.dependencies] +tzdata = {version = "*", markers = "platform_system == \"Windows\""} + +[package.extras] +devenv = ["check-manifest", "pytest (>=4.3)", "pytest-cov", "pytest-mock (>=3.3)", "zest.releaser"] + [[package]] name = "urllib3" version = "2.2.1" @@ -752,4 +780,4 @@ multidict = ">=4.0" [metadata] lock-version = "2.0" python-versions = "^3.11" -content-hash = "f94df9517f6942e31a03c96b92a1eb0851ea71c7a61e4443c4590c1a9cdf18a5" +content-hash = "00db07a343e8b8bce60fc60239cafdc0e1efa0cd9411e20dccf52b844506b83e" diff --git a/pyproject.toml b/pyproject.toml index 3a94605..3a12cfc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -16,6 +16,7 @@ dropbox = "^11.36.2" pytz = "^2024.1" pyyaml = "^6.0.1" python-dotenv = "^1.0.1" +tzlocal = "^5.2" [build-system]