discord-message-cli 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- discord_message_cli-0.1.0.dist-info/METADATA +177 -0
- discord_message_cli-0.1.0.dist-info/RECORD +14 -0
- discord_message_cli-0.1.0.dist-info/WHEEL +5 -0
- discord_message_cli-0.1.0.dist-info/entry_points.txt +2 -0
- discord_message_cli-0.1.0.dist-info/top_level.txt +1 -0
- discord_msg/__init__.py +3 -0
- discord_msg/aggregator.py +149 -0
- discord_msg/auth.py +59 -0
- discord_msg/cli.py +259 -0
- discord_msg/client.py +319 -0
- discord_msg/config.py +50 -0
- discord_msg/errors.py +60 -0
- discord_msg/formatter.py +100 -0
- discord_msg/time_utils.py +122 -0
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: discord-message-cli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Read-only Discord channel message aggregation CLI for humans and AI agents
|
|
5
|
+
License: MIT
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
Requires-Dist: tzdata; sys_platform == "win32"
|
|
9
|
+
|
|
10
|
+
# Discord Message CLI (`discord-msg`)
|
|
11
|
+
|
|
12
|
+
権限を持つ Discord チャンネルのメッセージを Discord 公式 HTTP API (v10) で**読み取り専用**で取得し、期間別の集計を行う CLI ツールです。
|
|
13
|
+
人がターミナルで表を確認するほか、AI エージェントやスクリプトが JSON 形式で安全に集計情報だけを取得できるように設計されています。
|
|
14
|
+
|
|
15
|
+
## 特徴とセキュリティ方針
|
|
16
|
+
|
|
17
|
+
- **読み取り専用**: `GET /channels/{channel_id}/messages` のみを使用し、投稿・編集・削除・権限変更の機能は一切持ちません。
|
|
18
|
+
- **本文・添付の非出力**: 接続確認(`check`)および期間集計(`stats`)の出力(表・JSON ともに)には、メッセージ本文・添付ファイル・トークンを一切含めません。
|
|
19
|
+
- **安全なトークン入力**: Bot トークンは環境変数(`DISCORD_BOT_TOKEN`)、対話的な非表示入力(`--prompt-token`)、または標準入力(`--token-stdin`)からのみ受け付けます。コマンドライン引数や設定ファイルには保存・指定できません。
|
|
20
|
+
- **標準出力と標準エラーの分離**: 診断メッセージやエラーはすべて標準エラー(`stderr`)に出力され、標準出力(`stdout`)には完全な結果(表または JSON)のみが出力されます。取得途中で失敗した場合は、不完全な集計を標準出力に出さず非ゼロ終了コードで終了します。
|
|
21
|
+
|
|
22
|
+
## 導入方法
|
|
23
|
+
|
|
24
|
+
Python 3.10 以上が必要です。`pipx` または `pip` でワンコマンド導入できます。
|
|
25
|
+
|
|
26
|
+
```powershell
|
|
27
|
+
# PyPI から導入する場合(推奨)
|
|
28
|
+
pipx install discord-message-cli
|
|
29
|
+
# または
|
|
30
|
+
pip install discord-message-cli
|
|
31
|
+
|
|
32
|
+
# GitHub リポジトリから直接導入する場合
|
|
33
|
+
pipx install git+https://github.com/IT-Engineer-K/discord-message-cli.git
|
|
34
|
+
|
|
35
|
+
# ローカルのクローンから導入する場合
|
|
36
|
+
pipx install .
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## 認証設定
|
|
40
|
+
|
|
41
|
+
実行前に環境変数 `DISCORD_BOT_TOKEN` を設定するか、実行時に `--prompt-token` を指定してください。
|
|
42
|
+
|
|
43
|
+
```powershell
|
|
44
|
+
# PowerShell で一時的に環境変数へ設定する例
|
|
45
|
+
$env:DISCORD_BOT_TOKEN = (Read-Host -AsSecureString "Bot Token" | ConvertFrom-SecureString -AsPlainText)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
> **必要な Discord Bot 権限**:
|
|
49
|
+
> 対象チャンネルに対する `View Channel`(チャンネルを見る)および `Read Message History`(メッセージ履歴を読む)。
|
|
50
|
+
> ※ 接頭辞(`--prefix`)やキーワード(`--keyword`)による本文絞り込みを行う場合は、Discord Developer Portal で Bot の **Message Content Intent** を有効にしてください。
|
|
51
|
+
|
|
52
|
+
## 使い方
|
|
53
|
+
|
|
54
|
+
### 1. 接続確認 (`check`)
|
|
55
|
+
|
|
56
|
+
対象チャンネルの履歴を読み取れるかを確認し、本文を表示せずに結果を返します。
|
|
57
|
+
|
|
58
|
+
```powershell
|
|
59
|
+
# 表形式(既定)
|
|
60
|
+
discord-msg check --channel 123456789012345678
|
|
61
|
+
|
|
62
|
+
# AI / スクリプト向け JSON 形式
|
|
63
|
+
discord-msg check --channel 123456789012345678 --format json
|
|
64
|
+
|
|
65
|
+
# トークンを対話的非表示入力で渡す場合
|
|
66
|
+
discord-msg check --channel 123456789012345678 --prompt-token
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
JSON 出力例:
|
|
70
|
+
|
|
71
|
+
```json
|
|
72
|
+
{
|
|
73
|
+
"ok": true,
|
|
74
|
+
"channel_id": "123456789012345678",
|
|
75
|
+
"reachable": true,
|
|
76
|
+
"history_readable": true,
|
|
77
|
+
"has_messages": true
|
|
78
|
+
}
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### 2. 期間別集計 (`stats`)
|
|
82
|
+
|
|
83
|
+
指定期間のメッセージ件数を集計します。
|
|
84
|
+
|
|
85
|
+
- **既定期間**: 直近 24 時間(`--since` / `--until` / `--hours` で変更可能。**開始時刻を含み、終了時刻は含まない** `[start, end)`)
|
|
86
|
+
- **既定タイムゾーン**: 日本時間 `Asia/Tokyo`(`--tz` で変更可能)
|
|
87
|
+
- **集計単位 (`--by`)**: `hour`(時間別・既定)、`day`(日別)、`total`(合計のみ)
|
|
88
|
+
- **絞り込み**: `--prefix`(本文の接頭辞)、`--keyword`(本文に含まれるキーワード)、`--ignore-case`(大文字・小文字を区別しない)
|
|
89
|
+
|
|
90
|
+
```powershell
|
|
91
|
+
# 直近24時間の時間別集計(日本時間・表形式)
|
|
92
|
+
discord-msg stats --channel 123456789012345678
|
|
93
|
+
|
|
94
|
+
# 期間と接頭辞・キーワードを指定して AI 向け JSON で取得
|
|
95
|
+
discord-msg stats `
|
|
96
|
+
--channel 123456789012345678 `
|
|
97
|
+
--since 2026-11-18T00:00:00+09:00 `
|
|
98
|
+
--until 2026-11-19T00:00:00+09:00 `
|
|
99
|
+
--by hour `
|
|
100
|
+
--prefix "[ALERT]" `
|
|
101
|
+
--keyword "DiskHigh" `
|
|
102
|
+
--format json
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
JSON 出力例:
|
|
106
|
+
|
|
107
|
+
```json
|
|
108
|
+
{
|
|
109
|
+
"channel_id": "123456789012345678",
|
|
110
|
+
"period": {
|
|
111
|
+
"start": "2026-11-18T09:00:00+09:00",
|
|
112
|
+
"end": "2026-11-18T12:00:00+09:00"
|
|
113
|
+
},
|
|
114
|
+
"timezone": "Asia/Tokyo",
|
|
115
|
+
"granularity": "hour",
|
|
116
|
+
"filter": {
|
|
117
|
+
"prefix": "[ALERT]",
|
|
118
|
+
"keyword": "DiskHigh",
|
|
119
|
+
"ignore_case": false
|
|
120
|
+
},
|
|
121
|
+
"buckets": [
|
|
122
|
+
{
|
|
123
|
+
"label": "2026-11-18 09:00",
|
|
124
|
+
"start": "2026-11-18T09:00:00+09:00",
|
|
125
|
+
"end": "2026-11-18T10:00:00+09:00",
|
|
126
|
+
"count": 2
|
|
127
|
+
},
|
|
128
|
+
{
|
|
129
|
+
"label": "2026-11-18 10:00",
|
|
130
|
+
"start": "2026-11-18T10:00:00+09:00",
|
|
131
|
+
"end": "2026-11-18T11:00:00+09:00",
|
|
132
|
+
"count": 0
|
|
133
|
+
},
|
|
134
|
+
{
|
|
135
|
+
"label": "2026-11-18 11:00",
|
|
136
|
+
"start": "2026-11-18T11:00:00+09:00",
|
|
137
|
+
"end": "2026-11-18T12:00:00+09:00",
|
|
138
|
+
"count": 3
|
|
139
|
+
}
|
|
140
|
+
],
|
|
141
|
+
"total": 5,
|
|
142
|
+
"scanned_in_period": 8
|
|
143
|
+
}
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
## ローカル設定ファイル(任意・非機密値のみ)
|
|
147
|
+
|
|
148
|
+
毎回 `--channel` を指定する代わりに、環境変数 `DISCORD_CHANNEL_ID` またはローカル設定ファイル(Windows の既定パス: `%APPDATA%\discord-msg\config.json`)に既定のチャンネル ID とタイムゾーンを記述できます。
|
|
149
|
+
※ セキュリティ保護のため、設定ファイルに `token` / `bot_token` キーが含まれている場合はエラーとして拒否します。
|
|
150
|
+
|
|
151
|
+
```json
|
|
152
|
+
{
|
|
153
|
+
"channel": "123456789012345678",
|
|
154
|
+
"tz": "Asia/Tokyo"
|
|
155
|
+
}
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## 終了コード一覧
|
|
159
|
+
|
|
160
|
+
| 終了コード | エラーコード | 意味 |
|
|
161
|
+
| :--- | :--- | :--- |
|
|
162
|
+
| `0` | - | 正常終了(履歴が空の場合も含む) |
|
|
163
|
+
| `2` | `INVALID_ARGS` | 引数・期間指定・設定ファイルの形式エラー |
|
|
164
|
+
| `3` | `AUTH_FAILED` | トークン未指定または認証失敗 (`401 Unauthorized`) |
|
|
165
|
+
| `4` | `PERMISSION_DENIED` | チャンネル閲覧・履歴読み取り権限不足 (`403 Forbidden`) |
|
|
166
|
+
| `5` | `NOT_FOUND` | チャンネルが存在しないかアクセス不可 (`404 Not Found`) |
|
|
167
|
+
| `6` | `RATE_LIMITED` | レート制限の再試行上限超過 (`429 Too Many Requests`) |
|
|
168
|
+
| `7` | `FETCH_FAILED` | 通信エラーやページ送り途中の API エラー(不完全な集計は返さない) |
|
|
169
|
+
|
|
170
|
+
## テストの実行
|
|
171
|
+
|
|
172
|
+
テストにはすべて架空のチャンネル ID・架空の通知データを使用しており、外部通信を行わずに実行できます。
|
|
173
|
+
|
|
174
|
+
```powershell
|
|
175
|
+
$env:PYTHONPATH="src"
|
|
176
|
+
python -m unittest discover -s tests -v
|
|
177
|
+
```
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
discord_msg/__init__.py,sha256=W30ISmZOgkpqpuzHJCIUCFvGYNDhC5y3jot2qCymzxg,58
|
|
2
|
+
discord_msg/aggregator.py,sha256=p1BBkhfNsgTndSo3YF6vv0N69YZwvueoVqADfch5jaE,4583
|
|
3
|
+
discord_msg/auth.py,sha256=1KfLnTUIzGutdMwgyz7YaIO597NIa1uKNyEG_o32KAI,1848
|
|
4
|
+
discord_msg/cli.py,sha256=bSups6c4BkLMQ1wyJhC8TCEKjC1L8nEs68wulTwKfE4,8174
|
|
5
|
+
discord_msg/client.py,sha256=-zcG8BHb3mDg66awPLqXan8Yc2NtktS__m3l5-vFBMk,11746
|
|
6
|
+
discord_msg/config.py,sha256=P3mRKl1KTThbgYpSnG918xBHyozlzX3okubMZoVP2zY,1544
|
|
7
|
+
discord_msg/errors.py,sha256=HGC59yKhBkRujstSE2M--bdv_Cc98CXtVk_8kY756kc,1459
|
|
8
|
+
discord_msg/formatter.py,sha256=9Nj67TXswmXixKrjuwcAn9r2hd75qRJ4HNO3RZyPga4,3699
|
|
9
|
+
discord_msg/time_utils.py,sha256=ODQMWmtIpFeWLSKmH2jGkq5efxVDe8iFDyJEjzphE5E,4117
|
|
10
|
+
discord_message_cli-0.1.0.dist-info/METADATA,sha256=CbG4OLop1SqyOMShD-E5zkKCW2mwjxKPM8mPzqp6ItY,7067
|
|
11
|
+
discord_message_cli-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
12
|
+
discord_message_cli-0.1.0.dist-info/entry_points.txt,sha256=9fFDOc7nPb8qTH3JFcua6OwW6rAHvrXjROsVp_5DDiw,53
|
|
13
|
+
discord_message_cli-0.1.0.dist-info/top_level.txt,sha256=LWvKAL_elfK1xF0Sf84jAEzio6KWJYt_XuLNyMrzFoQ,12
|
|
14
|
+
discord_message_cli-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
discord_msg
|
discord_msg/__init__.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""Message filtering and time-bucket aggregation without exposing message content."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from datetime import datetime, timedelta, tzinfo
|
|
7
|
+
from typing import Literal
|
|
8
|
+
|
|
9
|
+
from .client import MessageRecord
|
|
10
|
+
from .errors import InvalidArgumentsError
|
|
11
|
+
|
|
12
|
+
Granularity = Literal["hour", "day", "total"]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class MessageFilter:
|
|
17
|
+
prefix: str | None = None
|
|
18
|
+
keyword: str | None = None
|
|
19
|
+
ignore_case: bool = False
|
|
20
|
+
|
|
21
|
+
def matches(self, content: str) -> bool:
|
|
22
|
+
target = content.lower() if self.ignore_case else content
|
|
23
|
+
|
|
24
|
+
if self.prefix is not None:
|
|
25
|
+
pref = self.prefix.lower() if self.ignore_case else self.prefix
|
|
26
|
+
if not target.startswith(pref):
|
|
27
|
+
return False
|
|
28
|
+
|
|
29
|
+
if self.keyword is not None:
|
|
30
|
+
kw = self.keyword.lower() if self.ignore_case else self.keyword
|
|
31
|
+
if kw not in target:
|
|
32
|
+
return False
|
|
33
|
+
|
|
34
|
+
return True
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True)
|
|
38
|
+
class BucketCount:
|
|
39
|
+
label: str
|
|
40
|
+
start: datetime
|
|
41
|
+
end: datetime
|
|
42
|
+
count: int
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True)
|
|
46
|
+
class AggregationReport:
|
|
47
|
+
channel_id: str
|
|
48
|
+
timezone_name: str
|
|
49
|
+
start: datetime
|
|
50
|
+
end: datetime
|
|
51
|
+
granularity: Granularity
|
|
52
|
+
msg_filter: MessageFilter
|
|
53
|
+
buckets: list[BucketCount]
|
|
54
|
+
total_matched: int
|
|
55
|
+
total_in_window: int
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def generate_buckets(
|
|
59
|
+
start: datetime,
|
|
60
|
+
end: datetime,
|
|
61
|
+
granularity: Granularity,
|
|
62
|
+
tz: tzinfo,
|
|
63
|
+
) -> list[tuple[str, datetime, datetime]]:
|
|
64
|
+
"""Generate contiguous [bucket_start, bucket_end) intervals covering [start, end) in `tz`."""
|
|
65
|
+
local_start = start.astimezone(tz)
|
|
66
|
+
local_end = end.astimezone(tz)
|
|
67
|
+
|
|
68
|
+
if granularity == "total":
|
|
69
|
+
label = "total"
|
|
70
|
+
return [(label, local_start, local_end)]
|
|
71
|
+
|
|
72
|
+
if granularity == "hour":
|
|
73
|
+
cursor = local_start.replace(minute=0, second=0, microsecond=0)
|
|
74
|
+
intervals: list[tuple[str, datetime, datetime]] = []
|
|
75
|
+
while cursor < local_end:
|
|
76
|
+
next_cursor = cursor + timedelta(hours=1)
|
|
77
|
+
b_start = max(cursor, local_start)
|
|
78
|
+
b_end = min(next_cursor, local_end)
|
|
79
|
+
if b_start < b_end:
|
|
80
|
+
label = cursor.strftime("%Y-%m-%d %H:00")
|
|
81
|
+
intervals.append((label, b_start, b_end))
|
|
82
|
+
cursor = next_cursor
|
|
83
|
+
return intervals
|
|
84
|
+
|
|
85
|
+
if granularity == "day":
|
|
86
|
+
cursor = local_start.replace(hour=0, minute=0, second=0, microsecond=0)
|
|
87
|
+
intervals = []
|
|
88
|
+
while cursor < local_end:
|
|
89
|
+
next_cursor = cursor + timedelta(days=1)
|
|
90
|
+
b_start = max(cursor, local_start)
|
|
91
|
+
b_end = min(next_cursor, local_end)
|
|
92
|
+
if b_start < b_end:
|
|
93
|
+
label = cursor.strftime("%Y-%m-%d")
|
|
94
|
+
intervals.append((label, b_start, b_end))
|
|
95
|
+
cursor = next_cursor
|
|
96
|
+
return intervals
|
|
97
|
+
|
|
98
|
+
raise InvalidArgumentsError(f"Unsupported granularity: {granularity}")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def aggregate_messages(
|
|
102
|
+
*,
|
|
103
|
+
channel_id: str,
|
|
104
|
+
messages: list[MessageRecord],
|
|
105
|
+
start: datetime,
|
|
106
|
+
end: datetime,
|
|
107
|
+
tz: tzinfo,
|
|
108
|
+
timezone_name: str,
|
|
109
|
+
granularity: Granularity = "hour",
|
|
110
|
+
msg_filter: MessageFilter | None = None,
|
|
111
|
+
) -> AggregationReport:
|
|
112
|
+
"""Filter messages in [start, end) and count them per bucket."""
|
|
113
|
+
active_filter = msg_filter if msg_filter is not None else MessageFilter()
|
|
114
|
+
local_start = start.astimezone(tz)
|
|
115
|
+
local_end = end.astimezone(tz)
|
|
116
|
+
|
|
117
|
+
in_window = [m for m in messages if local_start <= m.timestamp.astimezone(tz) < local_end]
|
|
118
|
+
matched = [m for m in in_window if active_filter.matches(m.content)]
|
|
119
|
+
|
|
120
|
+
raw_intervals = generate_buckets(local_start, local_end, granularity, tz)
|
|
121
|
+
counts = [0] * len(raw_intervals)
|
|
122
|
+
|
|
123
|
+
if granularity == "total":
|
|
124
|
+
if counts:
|
|
125
|
+
counts[0] = len(matched)
|
|
126
|
+
else:
|
|
127
|
+
for msg in matched:
|
|
128
|
+
local_ts = msg.timestamp.astimezone(tz)
|
|
129
|
+
for idx, (_, b_start, b_end) in enumerate(raw_intervals):
|
|
130
|
+
if b_start <= local_ts < b_end:
|
|
131
|
+
counts[idx] += 1
|
|
132
|
+
break
|
|
133
|
+
|
|
134
|
+
buckets = [
|
|
135
|
+
BucketCount(label=label, start=b_start, end=b_end, count=counts[idx])
|
|
136
|
+
for idx, (label, b_start, b_end) in enumerate(raw_intervals)
|
|
137
|
+
]
|
|
138
|
+
|
|
139
|
+
return AggregationReport(
|
|
140
|
+
channel_id=channel_id,
|
|
141
|
+
timezone_name=timezone_name,
|
|
142
|
+
start=local_start,
|
|
143
|
+
end=local_end,
|
|
144
|
+
granularity=granularity,
|
|
145
|
+
msg_filter=active_filter,
|
|
146
|
+
buckets=buckets,
|
|
147
|
+
total_matched=len(matched),
|
|
148
|
+
total_in_window=len(in_window),
|
|
149
|
+
)
|
discord_msg/auth.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Secure Bot token resolution without command-line arguments or logging."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import getpass
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
from collections.abc import Mapping
|
|
9
|
+
|
|
10
|
+
from .errors import AuthFailedError, InvalidArgumentsError
|
|
11
|
+
|
|
12
|
+
DEFAULT_TOKEN_ENV = "DISCORD_BOT_TOKEN"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def resolve_token(
|
|
16
|
+
*,
|
|
17
|
+
prompt_token: bool = False,
|
|
18
|
+
token_stdin: bool = False,
|
|
19
|
+
env_var: str = DEFAULT_TOKEN_ENV,
|
|
20
|
+
env: Mapping[str, str] | None = None,
|
|
21
|
+
stdin: object | None = None,
|
|
22
|
+
) -> str:
|
|
23
|
+
"""Resolve the Discord Bot token securely.
|
|
24
|
+
|
|
25
|
+
Priority:
|
|
26
|
+
1. Explicit --token-stdin (reads first line from stdin)
|
|
27
|
+
2. Explicit --prompt-token (reads via getpass on stderr)
|
|
28
|
+
3. Environment variable (default: DISCORD_BOT_TOKEN)
|
|
29
|
+
4. Interactive prompt fallback if stdin is a TTY
|
|
30
|
+
"""
|
|
31
|
+
if prompt_token and token_stdin:
|
|
32
|
+
raise InvalidArgumentsError(
|
|
33
|
+
"--prompt-token and --token-stdin cannot be used together."
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
in_stream = stdin if stdin is not None else sys.stdin
|
|
37
|
+
environ = env if env is not None else os.environ
|
|
38
|
+
|
|
39
|
+
raw_token = ""
|
|
40
|
+
if token_stdin:
|
|
41
|
+
line = getattr(in_stream, "readline", lambda: "")()
|
|
42
|
+
raw_token = line.strip()
|
|
43
|
+
elif prompt_token:
|
|
44
|
+
raw_token = getpass.getpass("Discord Bot Token: ", stream=sys.stderr).strip()
|
|
45
|
+
else:
|
|
46
|
+
raw_token = environ.get(env_var, "").strip()
|
|
47
|
+
if not raw_token and hasattr(in_stream, "isatty") and in_stream.isatty():
|
|
48
|
+
raw_token = getpass.getpass("Discord Bot Token: ", stream=sys.stderr).strip()
|
|
49
|
+
|
|
50
|
+
if raw_token.lower().startswith("bot "):
|
|
51
|
+
raw_token = raw_token[4:].strip()
|
|
52
|
+
|
|
53
|
+
if not raw_token:
|
|
54
|
+
raise AuthFailedError(
|
|
55
|
+
f"Discord Bot token is not provided. Set the {env_var} environment variable "
|
|
56
|
+
"or use --prompt-token."
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
return raw_token
|
discord_msg/cli.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""Command-line entry point for Discord Message CLI."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
from collections.abc import Callable, Mapping
|
|
9
|
+
from datetime import datetime
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import TextIO
|
|
12
|
+
|
|
13
|
+
from . import __version__
|
|
14
|
+
from .aggregator import Granularity, MessageFilter, aggregate_messages
|
|
15
|
+
from .auth import DEFAULT_TOKEN_ENV, resolve_token
|
|
16
|
+
from .client import HttpTransport, ReadOnlyDiscordClient, validate_channel_id
|
|
17
|
+
from .config import load_local_config
|
|
18
|
+
from .errors import DiscordMsgError, ExitCode, InvalidArgumentsError
|
|
19
|
+
from .formatter import (
|
|
20
|
+
format_check_json,
|
|
21
|
+
format_check_table,
|
|
22
|
+
format_stats_json,
|
|
23
|
+
format_stats_table,
|
|
24
|
+
)
|
|
25
|
+
from .time_utils import resolve_timezone, resolve_window
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class _RaisingArgumentParser(argparse.ArgumentParser):
|
|
29
|
+
def error(self, message: str) -> None:
|
|
30
|
+
raise InvalidArgumentsError(message)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _add_common_options(parser: argparse.ArgumentParser) -> None:
|
|
34
|
+
parser.add_argument(
|
|
35
|
+
"-c",
|
|
36
|
+
"--channel",
|
|
37
|
+
help="Target Discord channel ID (numeric Snowflake). Also reads DISCORD_CHANNEL_ID or local config.",
|
|
38
|
+
)
|
|
39
|
+
parser.add_argument(
|
|
40
|
+
"--format",
|
|
41
|
+
choices=("table", "json"),
|
|
42
|
+
default="table",
|
|
43
|
+
help="Output format on stdout: 'table' for humans (default) or 'json' for AI agents/scripts.",
|
|
44
|
+
)
|
|
45
|
+
parser.add_argument(
|
|
46
|
+
"--prompt-token",
|
|
47
|
+
action="store_true",
|
|
48
|
+
help="Read Bot token interactively with hidden input on stderr.",
|
|
49
|
+
)
|
|
50
|
+
parser.add_argument(
|
|
51
|
+
"--token-stdin",
|
|
52
|
+
action="store_true",
|
|
53
|
+
help="Read Bot token from standard input (first line).",
|
|
54
|
+
)
|
|
55
|
+
parser.add_argument(
|
|
56
|
+
"--config",
|
|
57
|
+
type=Path,
|
|
58
|
+
default=None,
|
|
59
|
+
help="Path to optional local non-secret config JSON file.",
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
64
|
+
parser = _RaisingArgumentParser(
|
|
65
|
+
prog="discord-msg",
|
|
66
|
+
description="Read-only Discord channel message check and aggregation CLI.",
|
|
67
|
+
)
|
|
68
|
+
parser.add_argument(
|
|
69
|
+
"-V",
|
|
70
|
+
"--version",
|
|
71
|
+
action="version",
|
|
72
|
+
version=f"%(prog)s {__version__}",
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
subparsers = parser.add_subparsers(dest="subcommand")
|
|
76
|
+
|
|
77
|
+
# check subcommand
|
|
78
|
+
check_parser = subparsers.add_parser(
|
|
79
|
+
"check",
|
|
80
|
+
help="Verify connection and message history read permission without displaying message content.",
|
|
81
|
+
)
|
|
82
|
+
_add_common_options(check_parser)
|
|
83
|
+
|
|
84
|
+
# stats subcommand
|
|
85
|
+
stats_parser = subparsers.add_parser(
|
|
86
|
+
"stats",
|
|
87
|
+
help="Aggregate message counts by time period without outputting message content or attachments.",
|
|
88
|
+
)
|
|
89
|
+
_add_common_options(stats_parser)
|
|
90
|
+
stats_parser.add_argument(
|
|
91
|
+
"--since",
|
|
92
|
+
help="Start time (inclusive) in ISO 8601 format (e.g. 2026-11-17T00:00:00+09:00 or 2026-11-17).",
|
|
93
|
+
)
|
|
94
|
+
stats_parser.add_argument(
|
|
95
|
+
"--until",
|
|
96
|
+
help="End time (exclusive) in ISO 8601 format (defaults to current time).",
|
|
97
|
+
)
|
|
98
|
+
stats_parser.add_argument(
|
|
99
|
+
"--hours",
|
|
100
|
+
type=float,
|
|
101
|
+
default=None,
|
|
102
|
+
help="Lookback window in hours when --since/--until are omitted (default: 24).",
|
|
103
|
+
)
|
|
104
|
+
stats_parser.add_argument(
|
|
105
|
+
"--tz",
|
|
106
|
+
default=None,
|
|
107
|
+
help="Display and bucket timezone (default: Asia/Tokyo).",
|
|
108
|
+
)
|
|
109
|
+
stats_parser.add_argument(
|
|
110
|
+
"--by",
|
|
111
|
+
"--granularity",
|
|
112
|
+
dest="granularity",
|
|
113
|
+
choices=("hour", "day", "total"),
|
|
114
|
+
default="hour",
|
|
115
|
+
help="Aggregation bucket unit: 'hour' (default), 'day', or 'total'.",
|
|
116
|
+
)
|
|
117
|
+
stats_parser.add_argument(
|
|
118
|
+
"--prefix",
|
|
119
|
+
default=None,
|
|
120
|
+
help="Count only messages whose body starts with this prefix.",
|
|
121
|
+
)
|
|
122
|
+
stats_parser.add_argument(
|
|
123
|
+
"--keyword",
|
|
124
|
+
default=None,
|
|
125
|
+
help="Count only messages whose body contains this keyword.",
|
|
126
|
+
)
|
|
127
|
+
stats_parser.add_argument(
|
|
128
|
+
"-i",
|
|
129
|
+
"--ignore-case",
|
|
130
|
+
action="store_true",
|
|
131
|
+
help="Perform case-insensitive matching for --prefix and --keyword.",
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
return parser
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _resolve_channel_id(
|
|
138
|
+
arg_channel: str | None,
|
|
139
|
+
env: Mapping[str, str],
|
|
140
|
+
config_channel: str | None,
|
|
141
|
+
) -> str:
|
|
142
|
+
raw = arg_channel or env.get("DISCORD_CHANNEL_ID") or config_channel
|
|
143
|
+
if not raw:
|
|
144
|
+
raise InvalidArgumentsError(
|
|
145
|
+
"Target channel ID is required. Specify --channel <CHANNEL_ID> or set DISCORD_CHANNEL_ID."
|
|
146
|
+
)
|
|
147
|
+
return validate_channel_id(raw)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def run_cli(
|
|
151
|
+
argv: list[str] | None = None,
|
|
152
|
+
*,
|
|
153
|
+
env: Mapping[str, str] | None = None,
|
|
154
|
+
stdin: TextIO | None = None,
|
|
155
|
+
stdout: TextIO | None = None,
|
|
156
|
+
stderr: TextIO | None = None,
|
|
157
|
+
transport: HttpTransport | None = None,
|
|
158
|
+
sleep_fn: Callable[[float], None] | None = None,
|
|
159
|
+
now: datetime | None = None,
|
|
160
|
+
) -> int:
|
|
161
|
+
out_stream = stdout if stdout is not None else sys.stdout
|
|
162
|
+
err_stream = stderr if stderr is not None else sys.stderr
|
|
163
|
+
in_stream = stdin if stdin is not None else sys.stdin
|
|
164
|
+
environ = env if env is not None else os.environ
|
|
165
|
+
|
|
166
|
+
def diag(msg: str) -> None:
|
|
167
|
+
print(f"[discord-msg] {msg}", file=err_stream)
|
|
168
|
+
|
|
169
|
+
parser = build_parser()
|
|
170
|
+
try:
|
|
171
|
+
args = parser.parse_args(argv)
|
|
172
|
+
if not args.subcommand:
|
|
173
|
+
raise InvalidArgumentsError("A subcommand is required ('check' or 'stats'). Run with --help for usage.")
|
|
174
|
+
|
|
175
|
+
local_cfg = load_local_config(args.config)
|
|
176
|
+
channel_id = _resolve_channel_id(args.channel, environ, local_cfg.channel_id)
|
|
177
|
+
|
|
178
|
+
token = resolve_token(
|
|
179
|
+
prompt_token=args.prompt_token,
|
|
180
|
+
token_stdin=args.token_stdin,
|
|
181
|
+
env_var=DEFAULT_TOKEN_ENV,
|
|
182
|
+
env=environ,
|
|
183
|
+
stdin=in_stream,
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
client_kwargs: dict[str, object] = {
|
|
187
|
+
"transport": transport,
|
|
188
|
+
"diag_fn": diag,
|
|
189
|
+
}
|
|
190
|
+
if sleep_fn is not None:
|
|
191
|
+
client_kwargs["sleep_fn"] = sleep_fn
|
|
192
|
+
|
|
193
|
+
client = ReadOnlyDiscordClient(token, **client_kwargs) # type: ignore[arg-type]
|
|
194
|
+
|
|
195
|
+
if args.subcommand == "check":
|
|
196
|
+
result = client.check_channel_access(channel_id)
|
|
197
|
+
output = (
|
|
198
|
+
format_check_json(result)
|
|
199
|
+
if args.format == "json"
|
|
200
|
+
else format_check_table(result)
|
|
201
|
+
)
|
|
202
|
+
print(output, file=out_stream)
|
|
203
|
+
return int(ExitCode.OK)
|
|
204
|
+
|
|
205
|
+
if args.subcommand == "stats":
|
|
206
|
+
tz_input = args.tz or local_cfg.tz or "Asia/Tokyo"
|
|
207
|
+
tz_info, tz_label = resolve_timezone(tz_input)
|
|
208
|
+
start_dt, end_dt = resolve_window(
|
|
209
|
+
since=args.since,
|
|
210
|
+
until=args.until,
|
|
211
|
+
hours=args.hours,
|
|
212
|
+
tz=tz_info,
|
|
213
|
+
now=now,
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
messages, pages = client.fetch_messages_in_window(channel_id, start_dt, end_dt)
|
|
217
|
+
diag(
|
|
218
|
+
f"Fetched {len(messages)} message(s) in window across {pages} API page(s) "
|
|
219
|
+
f"[{start_dt.isoformat()} -> {end_dt.isoformat()}]."
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
msg_filter = MessageFilter(
|
|
223
|
+
prefix=args.prefix,
|
|
224
|
+
keyword=args.keyword,
|
|
225
|
+
ignore_case=args.ignore_case,
|
|
226
|
+
)
|
|
227
|
+
granularity: Granularity = args.granularity
|
|
228
|
+
report = aggregate_messages(
|
|
229
|
+
channel_id=channel_id,
|
|
230
|
+
messages=messages,
|
|
231
|
+
start=start_dt,
|
|
232
|
+
end=end_dt,
|
|
233
|
+
tz=tz_info,
|
|
234
|
+
timezone_name=tz_label,
|
|
235
|
+
granularity=granularity,
|
|
236
|
+
msg_filter=msg_filter,
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
output = (
|
|
240
|
+
format_stats_json(report)
|
|
241
|
+
if args.format == "json"
|
|
242
|
+
else format_stats_table(report)
|
|
243
|
+
)
|
|
244
|
+
print(output, file=out_stream)
|
|
245
|
+
return int(ExitCode.OK)
|
|
246
|
+
|
|
247
|
+
raise InvalidArgumentsError(f"Unknown subcommand: {args.subcommand}")
|
|
248
|
+
|
|
249
|
+
except DiscordMsgError as exc:
|
|
250
|
+
print(f"[discord-msg] error ({exc.code}): {exc.message}", file=err_stream)
|
|
251
|
+
return exc.exit_code
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def main() -> None:
|
|
255
|
+
sys.exit(run_cli())
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
if __name__ == "__main__":
|
|
259
|
+
main()
|
discord_msg/client.py
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
"""Read-only Discord HTTP API v10 client with pagination and rate-limit handling."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
import time
|
|
8
|
+
import urllib.error
|
|
9
|
+
import urllib.parse
|
|
10
|
+
import urllib.request
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from datetime import datetime
|
|
14
|
+
from typing import Any, Protocol
|
|
15
|
+
|
|
16
|
+
from .errors import (
|
|
17
|
+
AuthFailedError,
|
|
18
|
+
ChannelNotFoundError,
|
|
19
|
+
FetchInterruptedError,
|
|
20
|
+
InvalidArgumentsError,
|
|
21
|
+
PermissionDeniedError,
|
|
22
|
+
RateLimitExceededError,
|
|
23
|
+
)
|
|
24
|
+
from .time_utils import datetime_to_snowflake, parse_discord_timestamp
|
|
25
|
+
|
|
26
|
+
DISCORD_API_BASE = "https://discord.com/api/v10"
|
|
27
|
+
USER_AGENT = "DiscordBot (https://github.com/IT-Engineer-K/discord-message-cli, 0.1.0)"
|
|
28
|
+
PAGE_LIMIT = 100
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class HttpResponse:
|
|
33
|
+
status: int
|
|
34
|
+
headers: dict[str, str]
|
|
35
|
+
body: bytes
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class HttpTransport(Protocol):
|
|
39
|
+
def request(self, method: str, url: str, headers: dict[str, str], timeout: float) -> HttpResponse:
|
|
40
|
+
...
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class UrllibTransport:
|
|
44
|
+
"""Standard-library HTTP transport restricted to GET requests."""
|
|
45
|
+
|
|
46
|
+
def request(self, method: str, url: str, headers: dict[str, str], timeout: float) -> HttpResponse:
|
|
47
|
+
if method.upper() != "GET":
|
|
48
|
+
raise ValueError("Only read-only GET requests are allowed.")
|
|
49
|
+
|
|
50
|
+
req = urllib.request.Request(url, headers=headers, method="GET")
|
|
51
|
+
try:
|
|
52
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
53
|
+
resp_headers = {k.lower(): v for k, v in resp.headers.items()}
|
|
54
|
+
return HttpResponse(
|
|
55
|
+
status=resp.status,
|
|
56
|
+
headers=resp_headers,
|
|
57
|
+
body=resp.read(),
|
|
58
|
+
)
|
|
59
|
+
except urllib.error.HTTPError as exc:
|
|
60
|
+
resp_headers = {k.lower(): v for k, v in exc.headers.items()} if exc.headers else {}
|
|
61
|
+
body = exc.read() if exc.fp else b""
|
|
62
|
+
return HttpResponse(
|
|
63
|
+
status=exc.code,
|
|
64
|
+
headers=resp_headers,
|
|
65
|
+
body=body,
|
|
66
|
+
)
|
|
67
|
+
except urllib.error.URLError as exc:
|
|
68
|
+
raise FetchInterruptedError(f"Network error while contacting Discord API: {exc.reason}") from exc
|
|
69
|
+
except TimeoutError as exc:
|
|
70
|
+
raise FetchInterruptedError("Timed out while contacting Discord API.") from exc
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True)
|
|
74
|
+
class MessageRecord:
|
|
75
|
+
"""In-memory message representation used only for filtering and aggregation.
|
|
76
|
+
|
|
77
|
+
Note: `content` is never serialized into CLI output in check/stats commands.
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
id: str
|
|
81
|
+
timestamp: datetime
|
|
82
|
+
content: str
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass(frozen=True)
|
|
86
|
+
class CheckResult:
|
|
87
|
+
channel_id: str
|
|
88
|
+
reachable: bool
|
|
89
|
+
history_readable: bool
|
|
90
|
+
has_messages: bool
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def validate_channel_id(channel_id: str) -> str:
|
|
94
|
+
cleaned = channel_id.strip()
|
|
95
|
+
if not cleaned or not cleaned.isdigit():
|
|
96
|
+
raise InvalidArgumentsError(
|
|
97
|
+
f"Invalid channel ID '{channel_id}'. Channel ID must be a numeric Discord Snowflake."
|
|
98
|
+
)
|
|
99
|
+
return cleaned
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class ReadOnlyDiscordClient:
|
|
103
|
+
"""Read-only client for Discord REST API v10."""
|
|
104
|
+
|
|
105
|
+
def __init__(
|
|
106
|
+
self,
|
|
107
|
+
token: str,
|
|
108
|
+
*,
|
|
109
|
+
base_url: str = DISCORD_API_BASE,
|
|
110
|
+
transport: HttpTransport | None = None,
|
|
111
|
+
sleep_fn: Callable[[float], None] = time.sleep,
|
|
112
|
+
max_rate_limit_retries: int = 5,
|
|
113
|
+
timeout: float = 15.0,
|
|
114
|
+
diag_fn: Callable[[str], None] | None = None,
|
|
115
|
+
) -> None:
|
|
116
|
+
self._token = token
|
|
117
|
+
self._base_url = base_url.rstrip("/")
|
|
118
|
+
self._transport = transport if transport is not None else UrllibTransport()
|
|
119
|
+
self._sleep = sleep_fn
|
|
120
|
+
self._max_retries = max_rate_limit_retries
|
|
121
|
+
self._timeout = timeout
|
|
122
|
+
self._diag = diag_fn if diag_fn is not None else self._default_diag
|
|
123
|
+
|
|
124
|
+
@staticmethod
|
|
125
|
+
def _default_diag(msg: str) -> None:
|
|
126
|
+
print(f"[discord-msg] {msg}", file=sys.stderr)
|
|
127
|
+
|
|
128
|
+
def _headers(self) -> dict[str, str]:
|
|
129
|
+
return {
|
|
130
|
+
"Authorization": f"Bot {self._token}",
|
|
131
|
+
"User-Agent": USER_AGENT,
|
|
132
|
+
"Accept": "application/json",
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
def _get_json(self, path: str, query: dict[str, str] | None = None) -> Any:
|
|
136
|
+
url = f"{self._base_url}{path}"
|
|
137
|
+
if query:
|
|
138
|
+
url = f"{url}?{urllib.parse.urlencode(query)}"
|
|
139
|
+
|
|
140
|
+
attempts = 0
|
|
141
|
+
while True:
|
|
142
|
+
resp = self._transport.request("GET", url, self._headers(), self._timeout)
|
|
143
|
+
|
|
144
|
+
if resp.status == 200:
|
|
145
|
+
try:
|
|
146
|
+
return json.loads(resp.body.decode("utf-8"))
|
|
147
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
|
148
|
+
raise FetchInterruptedError("Invalid JSON response from Discord API.") from exc
|
|
149
|
+
|
|
150
|
+
if resp.status == 429:
|
|
151
|
+
retry_after = self._extract_retry_after(resp)
|
|
152
|
+
if attempts >= self._max_retries:
|
|
153
|
+
raise RateLimitExceededError(
|
|
154
|
+
f"Rate limit exceeded after {self._max_retries} retries (retry_after={retry_after}s)."
|
|
155
|
+
)
|
|
156
|
+
attempts += 1
|
|
157
|
+
self._diag(
|
|
158
|
+
f"Rate limited by Discord API (429). Waiting {retry_after:.2f}s before retry "
|
|
159
|
+
f"({attempts}/{self._max_retries})..."
|
|
160
|
+
)
|
|
161
|
+
self._sleep(retry_after)
|
|
162
|
+
continue
|
|
163
|
+
|
|
164
|
+
if resp.status == 401:
|
|
165
|
+
raise AuthFailedError("Discord authentication failed (401 Unauthorized). Check your Bot token.")
|
|
166
|
+
|
|
167
|
+
if resp.status == 403:
|
|
168
|
+
api_msg = self._extract_api_error_detail(resp)
|
|
169
|
+
raise PermissionDeniedError(
|
|
170
|
+
f"Missing permission to access channel history (403 Forbidden{api_msg}). "
|
|
171
|
+
"Ensure the Bot has 'View Channel' and 'Read Message History' permissions."
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
if resp.status == 404:
|
|
175
|
+
raise ChannelNotFoundError("Channel not found or inaccessible (404 Not Found).")
|
|
176
|
+
|
|
177
|
+
if 500 <= resp.status < 600:
|
|
178
|
+
raise FetchInterruptedError(
|
|
179
|
+
f"Discord API server error ({resp.status}) while fetching messages."
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
api_msg = self._extract_api_error_detail(resp)
|
|
183
|
+
raise FetchInterruptedError(
|
|
184
|
+
f"Unexpected HTTP status {resp.status} from Discord API{api_msg}."
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
@staticmethod
|
|
188
|
+
def _extract_retry_after(resp: HttpResponse) -> float:
|
|
189
|
+
try:
|
|
190
|
+
payload = json.loads(resp.body.decode("utf-8"))
|
|
191
|
+
if isinstance(payload, dict) and "retry_after" in payload:
|
|
192
|
+
return max(float(payload["retry_after"]), 0.0)
|
|
193
|
+
except (UnicodeDecodeError, json.JSONDecodeError, TypeError, ValueError):
|
|
194
|
+
pass
|
|
195
|
+
|
|
196
|
+
header_val = resp.headers.get("retry-after") or resp.headers.get("x-ratelimit-reset-after")
|
|
197
|
+
if header_val is not None:
|
|
198
|
+
try:
|
|
199
|
+
return max(float(header_val), 0.0)
|
|
200
|
+
except ValueError:
|
|
201
|
+
pass
|
|
202
|
+
|
|
203
|
+
return 1.0
|
|
204
|
+
|
|
205
|
+
@staticmethod
|
|
206
|
+
def _extract_api_error_detail(resp: HttpResponse) -> str:
|
|
207
|
+
try:
|
|
208
|
+
payload = json.loads(resp.body.decode("utf-8"))
|
|
209
|
+
if isinstance(payload, dict):
|
|
210
|
+
code = payload.get("code")
|
|
211
|
+
message = payload.get("message")
|
|
212
|
+
if code is not None and message:
|
|
213
|
+
return f": [{code}] {message}"
|
|
214
|
+
if message:
|
|
215
|
+
return f": {message}"
|
|
216
|
+
except (UnicodeDecodeError, json.JSONDecodeError):
|
|
217
|
+
pass
|
|
218
|
+
return ""
|
|
219
|
+
|
|
220
|
+
def check_channel_access(self, channel_id: str) -> CheckResult:
|
|
221
|
+
"""Verify that the Bot can read message history in the channel without returning content."""
|
|
222
|
+
cid = validate_channel_id(channel_id)
|
|
223
|
+
payload = self._get_json(f"/channels/{cid}/messages", {"limit": "1"})
|
|
224
|
+
if not isinstance(payload, list):
|
|
225
|
+
raise FetchInterruptedError("Unexpected payload structure from Discord messages endpoint.")
|
|
226
|
+
|
|
227
|
+
return CheckResult(
|
|
228
|
+
channel_id=cid,
|
|
229
|
+
reachable=True,
|
|
230
|
+
history_readable=True,
|
|
231
|
+
has_messages=len(payload) > 0,
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
def fetch_messages_in_window(
|
|
235
|
+
self,
|
|
236
|
+
channel_id: str,
|
|
237
|
+
start: datetime,
|
|
238
|
+
end: datetime,
|
|
239
|
+
) -> tuple[list[MessageRecord], int]:
|
|
240
|
+
"""Fetch all messages in [start, end) by paging backwards from `end`.
|
|
241
|
+
|
|
242
|
+
Uses a generous upper-bound snowflake for `end` (+1 second) on the first page
|
|
243
|
+
to ensure boundary messages are never missed, and stops once messages older
|
|
244
|
+
than `start` are reached or history is exhausted.
|
|
245
|
+
If any page fails mid-stream, raises FetchInterruptedError / RateLimitExceededError
|
|
246
|
+
so partial results are never mistaken for complete counts.
|
|
247
|
+
"""
|
|
248
|
+
cid = validate_channel_id(channel_id)
|
|
249
|
+
# Add 1000ms margin on initial cursor so messages right before `end` are included,
|
|
250
|
+
# then filter strictly by `start <= timestamp < end`.
|
|
251
|
+
from datetime import timedelta
|
|
252
|
+
|
|
253
|
+
before_cursor = datetime_to_snowflake(end + timedelta(seconds=1))
|
|
254
|
+
seen_ids: set[str] = set()
|
|
255
|
+
collected: list[MessageRecord] = []
|
|
256
|
+
pages_fetched = 0
|
|
257
|
+
|
|
258
|
+
while True:
|
|
259
|
+
query = {
|
|
260
|
+
"limit": str(PAGE_LIMIT),
|
|
261
|
+
"before": before_cursor,
|
|
262
|
+
}
|
|
263
|
+
payload = self._get_json(f"/channels/{cid}/messages", query)
|
|
264
|
+
if not isinstance(payload, list):
|
|
265
|
+
raise FetchInterruptedError("Unexpected payload structure from Discord messages endpoint.")
|
|
266
|
+
|
|
267
|
+
pages_fetched += 1
|
|
268
|
+
if not payload:
|
|
269
|
+
break
|
|
270
|
+
|
|
271
|
+
oldest_ts_in_page: datetime | None = None
|
|
272
|
+
oldest_id_in_page: str | None = None
|
|
273
|
+
|
|
274
|
+
for raw_msg in payload:
|
|
275
|
+
if not isinstance(raw_msg, dict):
|
|
276
|
+
raise FetchInterruptedError("Malformed message item in Discord API response.")
|
|
277
|
+
msg_id = str(raw_msg.get("id", "")).strip()
|
|
278
|
+
raw_ts = raw_msg.get("timestamp")
|
|
279
|
+
if not msg_id or not isinstance(raw_ts, str):
|
|
280
|
+
raise FetchInterruptedError("Message item missing required 'id' or 'timestamp' field.")
|
|
281
|
+
|
|
282
|
+
if msg_id in seen_ids:
|
|
283
|
+
continue
|
|
284
|
+
seen_ids.add(msg_id)
|
|
285
|
+
|
|
286
|
+
try:
|
|
287
|
+
msg_ts = parse_discord_timestamp(raw_ts)
|
|
288
|
+
except ValueError as exc:
|
|
289
|
+
raise FetchInterruptedError(str(exc)) from exc
|
|
290
|
+
|
|
291
|
+
if oldest_ts_in_page is None or msg_ts < oldest_ts_in_page:
|
|
292
|
+
oldest_ts_in_page = msg_ts
|
|
293
|
+
if oldest_id_in_page is None or int(msg_id) < int(oldest_id_in_page):
|
|
294
|
+
oldest_id_in_page = msg_id
|
|
295
|
+
|
|
296
|
+
if start <= msg_ts < end:
|
|
297
|
+
content = raw_msg.get("content")
|
|
298
|
+
text_content = content if isinstance(content, str) else ""
|
|
299
|
+
collected.append(
|
|
300
|
+
MessageRecord(
|
|
301
|
+
id=msg_id,
|
|
302
|
+
timestamp=msg_ts,
|
|
303
|
+
content=text_content,
|
|
304
|
+
)
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
if oldest_id_in_page is None or oldest_id_in_page == before_cursor:
|
|
308
|
+
break
|
|
309
|
+
|
|
310
|
+
before_cursor = oldest_id_in_page
|
|
311
|
+
|
|
312
|
+
if oldest_ts_in_page is not None and oldest_ts_in_page < start:
|
|
313
|
+
break
|
|
314
|
+
|
|
315
|
+
if len(payload) < PAGE_LIMIT:
|
|
316
|
+
break
|
|
317
|
+
|
|
318
|
+
collected.sort(key=lambda m: (m.timestamp, int(m.id)))
|
|
319
|
+
return collected, pages_fetched
|
discord_msg/config.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Local non-secret configuration loader."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from .errors import InvalidArgumentsError
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class LocalConfig:
|
|
16
|
+
channel_id: str | None = None
|
|
17
|
+
tz: str = "Asia/Tokyo"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def default_config_path() -> Path:
|
|
21
|
+
appdata = os.environ.get("APPDATA")
|
|
22
|
+
if appdata:
|
|
23
|
+
return Path(appdata) / "discord-msg" / "config.json"
|
|
24
|
+
return Path.home() / ".config" / "discord-msg" / "config.json"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def load_local_config(path: Path | None = None) -> LocalConfig:
|
|
28
|
+
cfg_path = path if path is not None else default_config_path()
|
|
29
|
+
if not cfg_path.exists():
|
|
30
|
+
return LocalConfig()
|
|
31
|
+
|
|
32
|
+
try:
|
|
33
|
+
raw: Any = json.loads(cfg_path.read_text(encoding="utf-8"))
|
|
34
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
35
|
+
raise InvalidArgumentsError(f"Failed to read config file {cfg_path}: {exc}") from exc
|
|
36
|
+
|
|
37
|
+
if not isinstance(raw, dict):
|
|
38
|
+
raise InvalidArgumentsError(f"Config file {cfg_path} must contain a JSON object.")
|
|
39
|
+
|
|
40
|
+
if "token" in raw or "bot_token" in raw:
|
|
41
|
+
raise InvalidArgumentsError(
|
|
42
|
+
f"Config file {cfg_path} must not store tokens. Use DISCORD_BOT_TOKEN or --prompt-token."
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
channel = raw.get("channel") or raw.get("channel_id")
|
|
46
|
+
tz = raw.get("tz", "Asia/Tokyo")
|
|
47
|
+
return LocalConfig(
|
|
48
|
+
channel_id=str(channel).strip() if channel is not None else None,
|
|
49
|
+
tz=str(tz).strip() if tz else "Asia/Tokyo",
|
|
50
|
+
)
|
discord_msg/errors.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Domain errors and exit codes for Discord Message CLI."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from enum import IntEnum
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ExitCode(IntEnum):
|
|
9
|
+
OK = 0
|
|
10
|
+
INVALID_ARGS = 2
|
|
11
|
+
AUTH_FAILED = 3
|
|
12
|
+
PERMISSION_DENIED = 4
|
|
13
|
+
NOT_FOUND = 5
|
|
14
|
+
RATE_LIMITED = 6
|
|
15
|
+
FETCH_FAILED = 7
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class DiscordMsgError(Exception):
|
|
19
|
+
"""Base error with stable error code and exit code."""
|
|
20
|
+
|
|
21
|
+
code: str = "ERROR"
|
|
22
|
+
exit_code: int = int(ExitCode.FETCH_FAILED)
|
|
23
|
+
|
|
24
|
+
def __init__(self, message: str, *, code: str | None = None, exit_code: int | None = None) -> None:
|
|
25
|
+
super().__init__(message)
|
|
26
|
+
self.message = message
|
|
27
|
+
if code is not None:
|
|
28
|
+
self.code = code
|
|
29
|
+
if exit_code is not None:
|
|
30
|
+
self.exit_code = int(exit_code)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class InvalidArgumentsError(DiscordMsgError):
|
|
34
|
+
code = "INVALID_ARGS"
|
|
35
|
+
exit_code = int(ExitCode.INVALID_ARGS)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class AuthFailedError(DiscordMsgError):
|
|
39
|
+
code = "AUTH_FAILED"
|
|
40
|
+
exit_code = int(ExitCode.AUTH_FAILED)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class PermissionDeniedError(DiscordMsgError):
|
|
44
|
+
code = "PERMISSION_DENIED"
|
|
45
|
+
exit_code = int(ExitCode.PERMISSION_DENIED)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class ChannelNotFoundError(DiscordMsgError):
|
|
49
|
+
code = "NOT_FOUND"
|
|
50
|
+
exit_code = int(ExitCode.NOT_FOUND)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class RateLimitExceededError(DiscordMsgError):
|
|
54
|
+
code = "RATE_LIMITED"
|
|
55
|
+
exit_code = int(ExitCode.RATE_LIMITED)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class FetchInterruptedError(DiscordMsgError):
|
|
59
|
+
code = "FETCH_FAILED"
|
|
60
|
+
exit_code = int(ExitCode.FETCH_FAILED)
|
discord_msg/formatter.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Human-readable table and AI-friendly JSON output formatters."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from .aggregator import AggregationReport
|
|
9
|
+
from .client import CheckResult
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def format_check_json(result: CheckResult) -> str:
|
|
13
|
+
payload: dict[str, Any] = {
|
|
14
|
+
"ok": result.reachable and result.history_readable,
|
|
15
|
+
"channel_id": result.channel_id,
|
|
16
|
+
"reachable": result.reachable,
|
|
17
|
+
"history_readable": result.history_readable,
|
|
18
|
+
"has_messages": result.has_messages,
|
|
19
|
+
}
|
|
20
|
+
return json.dumps(payload, ensure_ascii=False, indent=2)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def format_check_table(result: CheckResult) -> str:
|
|
24
|
+
status = "OK" if (result.reachable and result.history_readable) else "NG"
|
|
25
|
+
history_state = "Readable (has messages)" if result.has_messages else "Readable (empty history)"
|
|
26
|
+
lines = [
|
|
27
|
+
f"Connection Check : {status}",
|
|
28
|
+
f"Channel ID : {result.channel_id}",
|
|
29
|
+
f"History Access : {history_state}",
|
|
30
|
+
]
|
|
31
|
+
return "\n".join(lines)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def format_stats_json(report: AggregationReport) -> str:
|
|
35
|
+
payload: dict[str, Any] = {
|
|
36
|
+
"channel_id": report.channel_id,
|
|
37
|
+
"period": {
|
|
38
|
+
"start": report.start.isoformat(),
|
|
39
|
+
"end": report.end.isoformat(),
|
|
40
|
+
},
|
|
41
|
+
"timezone": report.timezone_name,
|
|
42
|
+
"granularity": report.granularity,
|
|
43
|
+
"filter": {
|
|
44
|
+
"prefix": report.msg_filter.prefix,
|
|
45
|
+
"keyword": report.msg_filter.keyword,
|
|
46
|
+
"ignore_case": report.msg_filter.ignore_case,
|
|
47
|
+
},
|
|
48
|
+
"buckets": [
|
|
49
|
+
{
|
|
50
|
+
"label": b.label,
|
|
51
|
+
"start": b.start.isoformat(),
|
|
52
|
+
"end": b.end.isoformat(),
|
|
53
|
+
"count": b.count,
|
|
54
|
+
}
|
|
55
|
+
for b in report.buckets
|
|
56
|
+
],
|
|
57
|
+
"total": report.total_matched,
|
|
58
|
+
"scanned_in_period": report.total_in_window,
|
|
59
|
+
}
|
|
60
|
+
return json.dumps(payload, ensure_ascii=False, indent=2)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def format_stats_table(report: AggregationReport) -> str:
|
|
64
|
+
filter_parts: list[str] = []
|
|
65
|
+
if report.msg_filter.prefix is not None:
|
|
66
|
+
filter_parts.append(f"prefix={report.msg_filter.prefix!r}")
|
|
67
|
+
if report.msg_filter.keyword is not None:
|
|
68
|
+
filter_parts.append(f"keyword={report.msg_filter.keyword!r}")
|
|
69
|
+
if filter_parts and report.msg_filter.ignore_case:
|
|
70
|
+
filter_parts.append("ignore_case=True")
|
|
71
|
+
filter_desc = ", ".join(filter_parts) if filter_parts else "all messages"
|
|
72
|
+
|
|
73
|
+
lines = [
|
|
74
|
+
f"Channel ID : {report.channel_id}",
|
|
75
|
+
f"Period : {report.start.isoformat()} -> {report.end.isoformat()} (start inclusive, end exclusive)",
|
|
76
|
+
f"Timezone : {report.timezone_name}",
|
|
77
|
+
f"Granularity : {report.granularity}",
|
|
78
|
+
f"Filter : {filter_desc}",
|
|
79
|
+
"",
|
|
80
|
+
]
|
|
81
|
+
|
|
82
|
+
if report.granularity != "total":
|
|
83
|
+
col1_header = "Bucket"
|
|
84
|
+
col2_header = "Count"
|
|
85
|
+
col1_width = max([len(col1_header)] + [len(b.label) for b in report.buckets])
|
|
86
|
+
col2_width = max([len(col2_header)] + [len(str(b.count)) for b in report.buckets] + [len(str(report.total_matched))])
|
|
87
|
+
|
|
88
|
+
sep = f"+-{'-' * col1_width}-+-{'-' * col2_width}-+"
|
|
89
|
+
lines.append(sep)
|
|
90
|
+
lines.append(f"| {col1_header.ljust(col1_width)} | {col2_header.rjust(col2_width)} |")
|
|
91
|
+
lines.append(sep)
|
|
92
|
+
for b in report.buckets:
|
|
93
|
+
lines.append(f"| {b.label.ljust(col1_width)} | {str(b.count).rjust(col2_width)} |")
|
|
94
|
+
lines.append(sep)
|
|
95
|
+
lines.append(f"| {'Total'.ljust(col1_width)} | {str(report.total_matched).rjust(col2_width)} |")
|
|
96
|
+
lines.append(sep)
|
|
97
|
+
else:
|
|
98
|
+
lines.append(f"Total : {report.total_matched}")
|
|
99
|
+
|
|
100
|
+
return "\n".join(lines)
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Time parsing, timezone conversion, andDiscord Snowflake utilities."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import datetime, timedelta, timezone, tzinfo
|
|
6
|
+
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
|
7
|
+
|
|
8
|
+
from .errors import InvalidArgumentsError
|
|
9
|
+
|
|
10
|
+
DISCORD_EPOCH_MS = 1420070400000
|
|
11
|
+
JST_FIXED = timezone(timedelta(hours=9), name="Asia/Tokyo")
|
|
12
|
+
|
|
13
|
+
_TZ_ALIASES = {
|
|
14
|
+
"JST": "Asia/Tokyo",
|
|
15
|
+
"ASIA/TOKYO": "Asia/Tokyo",
|
|
16
|
+
"UTC": "UTC",
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def resolve_timezone(tz_name: str) -> tuple[tzinfo, str]:
|
|
21
|
+
"""Return a tzinfo instance and normalized timezone label."""
|
|
22
|
+
cleaned = tz_name.strip()
|
|
23
|
+
if not cleaned:
|
|
24
|
+
raise InvalidArgumentsError("Timezone name cannot be empty.")
|
|
25
|
+
|
|
26
|
+
canonical = _TZ_ALIASES.get(cleaned.upper(), cleaned)
|
|
27
|
+
if canonical == "UTC":
|
|
28
|
+
return timezone.utc, "UTC"
|
|
29
|
+
|
|
30
|
+
try:
|
|
31
|
+
return ZoneInfo(canonical), canonical
|
|
32
|
+
except ZoneInfoNotFoundError as exc:
|
|
33
|
+
if canonical == "Asia/Tokyo":
|
|
34
|
+
return JST_FIXED, "Asia/Tokyo"
|
|
35
|
+
raise InvalidArgumentsError(f"Unknown timezone: {tz_name}") from exc
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def parse_user_datetime(value: str, default_tz: tzinfo) -> datetime:
|
|
39
|
+
"""Parse an ISO-8601 date or datetime string into a timezone-aware datetime.
|
|
40
|
+
|
|
41
|
+
If `value` is date-only (YYYY-MM-DD), 00:00:00 in `default_tz` is assumed.
|
|
42
|
+
If `value` has no offset, `default_tz` is attached.
|
|
43
|
+
"""
|
|
44
|
+
text = value.strip()
|
|
45
|
+
if not text:
|
|
46
|
+
raise InvalidArgumentsError("Datetime value cannot be empty.")
|
|
47
|
+
|
|
48
|
+
if text.endswith("Z") or text.endswith("z"):
|
|
49
|
+
text = text[:-1] + "+00:00"
|
|
50
|
+
|
|
51
|
+
try:
|
|
52
|
+
if len(text) == 10 and text[4] == "-" and text[7] == "-":
|
|
53
|
+
dt = datetime.strptime(text, "%Y-%m-%d")
|
|
54
|
+
return dt.replace(tzinfo=default_tz)
|
|
55
|
+
dt = datetime.fromisoformat(text)
|
|
56
|
+
except ValueError as exc:
|
|
57
|
+
raise InvalidArgumentsError(
|
|
58
|
+
f"Invalid date/datetime format '{value}'. Expected ISO 8601 (e.g. 2026-11-18T00:00:00+09:00 or 2026-11-18)."
|
|
59
|
+
) from exc
|
|
60
|
+
|
|
61
|
+
if dt.tzinfo is None:
|
|
62
|
+
dt = dt.replace(tzinfo=default_tz)
|
|
63
|
+
return dt.astimezone(default_tz)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def parse_discord_timestamp(value: str) -> datetime:
|
|
67
|
+
"""Parse a Discord API message timestamp into an aware UTC datetime."""
|
|
68
|
+
text = value.strip()
|
|
69
|
+
if text.endswith("Z") or text.endswith("z"):
|
|
70
|
+
text = text[:-1] + "+00:00"
|
|
71
|
+
try:
|
|
72
|
+
dt = datetime.fromisoformat(text)
|
|
73
|
+
except ValueError as exc:
|
|
74
|
+
raise ValueError(f"Invalid Discord timestamp: {value}") from exc
|
|
75
|
+
if dt.tzinfo is None:
|
|
76
|
+
dt = dt.replace(tzinfo=timezone.utc)
|
|
77
|
+
return dt.astimezone(timezone.utc)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def resolve_window(
|
|
81
|
+
*,
|
|
82
|
+
since: str | None,
|
|
83
|
+
until: str | None,
|
|
84
|
+
hours: float | None,
|
|
85
|
+
tz: tzinfo,
|
|
86
|
+
now: datetime | None = None,
|
|
87
|
+
) -> tuple[datetime, datetime]:
|
|
88
|
+
"""Resolve the [start, end) aggregation window in the target timezone."""
|
|
89
|
+
if hours is not None and (since is not None or until is not None):
|
|
90
|
+
raise InvalidArgumentsError("--hours cannot be combined with --since or --until.")
|
|
91
|
+
if hours is not None and hours <= 0:
|
|
92
|
+
raise InvalidArgumentsError("--hours must be greater than 0.")
|
|
93
|
+
|
|
94
|
+
current = (now if now is not None else datetime.now(timezone.utc)).astimezone(tz)
|
|
95
|
+
|
|
96
|
+
if until is not None:
|
|
97
|
+
end_dt = parse_user_datetime(until, tz)
|
|
98
|
+
else:
|
|
99
|
+
end_dt = current
|
|
100
|
+
|
|
101
|
+
if since is not None:
|
|
102
|
+
start_dt = parse_user_datetime(since, tz)
|
|
103
|
+
else:
|
|
104
|
+
span_hours = hours if hours is not None else 24.0
|
|
105
|
+
start_dt = end_dt - timedelta(hours=span_hours)
|
|
106
|
+
|
|
107
|
+
if start_dt >= end_dt:
|
|
108
|
+
raise InvalidArgumentsError(
|
|
109
|
+
f"Start time ({start_dt.isoformat()}) must be earlier than end time ({end_dt.isoformat()})."
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
return start_dt, end_dt
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def datetime_to_snowflake(dt: datetime) -> str:
|
|
116
|
+
"""Convert a datetime to a synthetic Discord Snowflake ID (lower bound at that millisecond)."""
|
|
117
|
+
utc_dt = dt.astimezone(timezone.utc)
|
|
118
|
+
unix_ms = int(utc_dt.timestamp() * 1000)
|
|
119
|
+
if unix_ms <= DISCORD_EPOCH_MS:
|
|
120
|
+
return "0"
|
|
121
|
+
snowflake = (unix_ms - DISCORD_EPOCH_MS) << 22
|
|
122
|
+
return str(snowflake)
|