using-mtcute について
using-mtcuteは、TelegramのネイティブMTProto API向け型安全ライブラリmtcuteをTypeScript開発者が使うためのスキルです。プラットフォーム別パッケージ、クライアントメソッド、更新処理、APIの型やシグネチャを調べる付属ツールを説明します。
主な機能
- 01対象環境に合うmtcuteパッケージを選択
- 02Telegramクライアントの認証とライフサイクルを設定
- 03高レベルメソッドでTelegram APIを操作
- 04Dispatcherで更新をルーティング
- 05メソッド、クラス、TL定義を検索
活用シーン
- 01TypeScriptでTelegramクライアントを構築
- 02メッセージと更新処理を実装
- 03高レベルAPIや生のTL呼び出しのシグネチャを確認
MCP 対応
READMEではmtcuteのドキュメント参照にContext7 MCPを任意で利用できるとしています。MCPサーバーやクライアントの実装については説明されていません。
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ mtcute/ mtcute --skill using-mtcuteインストール後、Claude Code で/using-mtcuteを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
tools/get-class.jsget-constructor.jsget-method.js詳細
mtcute — TypeScript MTProto ライブラリ
mtcute とは?
mtcute は、Telegram の MTProto プロトコルに対応した、最新の型安全な TypeScript ライブラリです。Bot API ラッパー(grammy、telegraf、node-telegram-bot-api)とは異なり、mtcute は Telegram のネイティブなバイナリプロトコルを直接使用するため、ボット向けの一部機能だけでなく、Telegram API のすべてにアクセスできます。
アーキテクチャの概要
コアパッケージ(通常は直接使用しません):
- @mtcute/core:MTProto クライアント、高レベルメソッド、TL スキーマ、型
- @mtcute/html-parser:HTML ↔ Telegram エンティティ
- @mtcute/markdown-parser:Markdown ↔ Telegram エンティティ
- @mtcute/file-id:Bot API の file_id 解析
プラットフォームパッケージ(対象プラットフォームに合ったものを使用してください):
- @mtcute/node、@mtcute/bun、@mtcute/deno:サーバーサイド JavaScript 用のランタイムバインディング
- @mtcute/web:ブラウザー用バインディング(IndexedDB、WebCrypto、WebSocket)
追加パッケージ(対応する特定の機能にのみ使用してください):
- @mtcute/dispatcher:更新のルーティング、フィルター、ボットフレームワーク
- @mtcute/convert:ほかのライブラリからのセッションのインポート
- @mtcute/test:単体テスト用ヘルパー
@mtcute/core ではなく、常にプラットフォームパッケージからすべてをインストールしてインポートしてください。
// ✅ Correct — platform package pre-configures crypto, transport, storage
import { TelegramClient } from '@mtcute/node'
// ❌ Wrong — raw core client requires manual platform setup
import { TelegramClient } from '@mtcute/core'
基本的な使い方
クライアントの作成
import { TelegramClient } from '@mtcute/node'
const tg = new TelegramClient({
apiId: Number(process.env.API_ID),
apiHash: process.env.API_HASH,
storage: 'my-account', // SQLite file name (Node.js)
})
クライアントのライフサイクル
TelegramClient を作成すると、disconnected 状態で起動します。
ほとんどの場合、start メソッドを使用して接続と認証を行います。
// Bot login
const self = await tg.start({ botToken: process.env.BOT_TOKEN })
// User login (interactive)
const self = await tg.start({
phone: () => input('Phone: '),
code: () => input('Code: '),
password: () => input('2FA password: '),
})
ただし、場合によってはライフサイクルを手動で制御することもできます。
// Manually connect
await tg.connect()
// Manually disconnect
await tg.disconnect()
// Disconnect and destroy the instance
await tg.destroy()
高レベルメソッドの呼び出し
TelegramClient クラスには、300 を超える便利な高レベルメソッドがあります。よく使われるメソッドを以下に示します。
- メッセージ:
sendText、sendMedia、getHistory、editMessage、deleteMessages、forwardMessages、searchMessages、... - チャット:
getChat、getChatMember、banChatMember、setChatTitle、setChatPhoto、... - ユーザー:
getUsers、getMe、setMyProfilePhoto、... - ファイル:
downloadFile、uploadFile、downloadAsStream、... - ダイアログ:
getDialogs、getPeerDialogs、... - ボット:
answerInlineQuery、answerCallbackQuery、setMyCommands、... - フォーラム:
createForumTopic、editForumTopic、... - ステッカー:
getStickerSet、createStickerSet、... - ストーリー:
sendStory、getStories、... - 認証:
start、logOut、sendCode、... - パスワード:
enable2fa、change2fa、...
// Send a text message
await tg.sendText('me', 'Hello!')
// Send with formatting
await tg.sendText(chatId, html`Hello, <b>${name}</b>!`)
// Send media
await tg.sendMedia(chatId, {
type: 'photo',
file: 'file:./photo.jpg', // note the file: prefix!
caption: 'Check this out',
})
// Get chat info
const chat = await tg.getChat('username')
// Download file
await tg.downloadToFile('path/to/save.jpg', photo)
一部のメソッドには、単一の引数ではなく配列を受け取る「バッチ」版があります。
const durov = await tg.getUser('durov')
const [durov, telegram] = await tg.getUsers(['durov', 'telegram'])
// Similarly with `getChat` and `getChats`, `getPeer` and `getPeers`
これらを取り違えないようにしてください。メソッド名が複数形の場合、配列を返す、または受け取る可能性が高いため、その点に留意してください。
ピアの解決
mtcute の高レベルメソッドでは、チャットやユーザーの引数に InputPeerLike を指定できます。指定できる値は次のとおりです。
- 数値 ID:
123456789 - ユーザー名の文字列:
'username' - 現在のユーザーを表す
'me'/'self' tl.TypeInputPeerオブジェクト- 高レベルオブジェクト(
User、Chat、Messageなど)
Dispatcher による更新の処理
import { Dispatcher, filters } from '@mtcute/dispatcher'
const dp = Dispatcher.for(tg)
dp.onNewMessage(filters.chat('private'), async (msg) => {
await msg.replyText('Hello!')
})
dp.onNewMessage(filters.command('start'), async (msg) => {
await msg.replyText('Welcome!')
})
dp.onCallbackQuery(filters.dataPrefix('btn_'), async (query) => {
await query.answer({ text: 'Clicked!' })
})
// Start receiving updates
await tg.startUpdatesLoop()
生の TL メソッド呼び出し
高レベル API でラップされていないメソッドには、.call() を使用してください。
const result = await tg.call({
_: 'messages.getEmojiKeywords',
langCode: 'en',
})
// result is fully typed based on the method's return type
TL 型システム
mtcute は Telegram の TL スキーマから TypeScript 型を生成します。すべての型は tl 名前空間にあります。
import { tl } from '@mtcute/core'
| TL の概念 | TypeScript 名 | 例 |
|---|---|---|
オブジェクト user | tl.RawUser | { _: 'user', id: number, ... } |
名前空間付きオブジェクト messages.chats | tl.messages.RawChats | |
メソッド users.getUsers | tl.users.RawGetUsersRequest | |
| 共用体型 | tl.TypeUser | tl.RawUser | tl.RawUserEmpty |
すべての TL オブジェクトには、コンストラクター名を表す判別フィールド _ があります(例:_: 'user')。
型ガードとして、tl.isAnyPeer()、tl.isAnyMessage() などを利用できます。
TL スキーマ全体は、@mtcute/node/tl/api-schema.json(または任意のプラットフォームパッケージ)で JSON として利用できます。形式:
{
"l": 223, // layer number
"e": [ // array of TL entries
{
"kind": "class" | "method",
"name": "user",
"id": 826896937, // constructor ID
"type": "User", // return/union type
"arguments": [{
"name": "id",
"type": "int53", // base type name (union or primitive)
"typeModifiers"?: {
"predicate"?: "flags.0", // conditional field, e.g. "flags.3"
"isVector"?: true, // optional: when true, type is actually Vector<type>
}
}, ...],
"comment": "..."
},
...
],
"u": { "User": "..." } // union comments
}
typeModifiers.predicate が設定されている場合(例:"flags.3")、そのフィールドは省略可能で、flags フィールドのビット 3 が設定されている場合にのみ存在します。isVector が true の場合、実際の型は Vector<type> です。
型とメソッドシグネチャの検索
バンドルされている 3 つのツールは、インストール済みの @mtcute/* パッケージの node_modules から情報を読み取ります。いずれもあいまい検索と誤字の自動修正に対応しています。
使い分け:
- TL の生の型/メソッド定義や、その TS インターフェースが必要な場合 →
get-constructor - 高レベルクライアントメソッドのシグネチャ(パラメーター、戻り値の型、JSDoc)が必要な場合 →
get-method - 高レベルのラッパークラス/インターフェース(Message、Chat など)の定義が必要な場合 →
get-class - 生の API 呼び出しで必要な TL パラメーターを確認したい場合 →
get-constructor --with-references - どのメソッド/クラスを使うべきか分からない場合 →
get-method --searchまたはget-class --search
get-constructor:TL スキーマの検索
TL 定義、TypeScript 型、共用体への所属、戻り値の型を表示します。
node .claude/skills/using-mtcute/tools/get-constructor.js <name>
node .claude/skills/using-mtcute/tools/get-constructor.js --with-references <name>
次のいずれの形式でも入力できます:
- TL 名:
user、messages.sendMessage - TS 型名:
RawUser、TypeInputUser、tl.messages.RawChats、messages.RawGetHistoryRequest
コンストラクターの引数や戻り値で参照される型を確認するには、--with-references を使います。出力に、参照されているすべてのコンストラクター/共用体が追加されます。
get-method:高レベルクライアントメソッドの検索
TelegramClient の完全な JSDoc とメソッドシグネチャを表示します。
node .claude/skills/using-mtcute/tools/get-method.js <method-name>
node .claude/skills/using-mtcute/tools/get-method.js --search <keyword>
node .claude/skills/using-mtcute/tools/get-method.js --list
- デフォルトモード:メソッド名を完全一致/あいまい一致で検索し、該当しない場合は名前、次に説明文の部分一致で検索します
--search:メソッド名と説明文の両方を検索し、一致する項目をすべて表示します--list:利用可能なすべてのメソッドを、1 行の説明とともに表示します
get-class:高レベル型/クラスの検索
highlevel/types/ にある、すべてのメンバーを含むクラス/インターフェース/型の完全な定義を表示します。
node .claude/skills/using-mtcute/tools/get-class.js <name>
node .claude/skills/using-mtcute/tools/get-class.js --no-members <name>
node .claude/skills/using-mtcute/tools/get-class.js --search <keyword>
node .claude/skills/using-mtcute/tools/get-class.js --list
- デフォルトモード:エクスポート名を完全一致/あいまい一致で検索し、すべてのメンバーを含む完全な定義を表示します
--no-members:本体ではなく、宣言行と JSDoc のみを表示します--search:名前と説明文の両方を検索し、一致する項目をすべて表示します(例:--search keyboard)--list:利用可能なすべてのエクスポートを、1 行の説明とともに表示します
高レベル型
mtcute は、生の TL オブジェクトを便利なヘルパーメソッド付きのクラスでラップします。
Message—tl.RawMessageをラップし、.replyText()、.editText()、.delete()、.forward()などを備えていますChat— チャンネル/グループ/ユーザーのチャット情報をラップしますUser—tl.RawUserをラップしますDocument、Photo、Video、Audio、Voice、Sticker— メディア型InlineQuery、CallbackQuery、ChatJoinRequest— 更新型
これらは node_modules/@mtcute/core/dist/highlevel/types/ にあります。
テキストの書式設定
mtcute は、書式設定用のタグ付きテンプレートリテラルに対応しています。
import { html, md } from '@mtcute/node'
await tg.sendText(chat, html`<b>Bold</b> and <i>italic</i>`)
await tg.sendText(chat, md`**Bold** and *italic*`)
html タグと md タグは、変数を埋め込む際のエスケープを自動で処理します。
よくあるパターン
エラー処理
import { tl } from '@mtcute/node'
try {
await tg.sendText(chatId, 'hello')
} catch (e) {
if (tl.RpcError.is(e, 'FLOOD_WAIT_%d')) {
console.log(`Rate limited, wait ${e.seconds}s`)
}
}
メディアの送信
import { InputMedia } from '@mtcute/node'
// Upload from path (note the file: prefix!)
await tg.sendMedia(chatId, InputMedia.document('file:/path/to/file.pdf', {
fileName: 'report.pdf',
}))
// Upload from buffer/stream
await tg.sendMedia(chatId, InputMedia.photo(buffer))
// Upload from URL
await tg.sendMedia(chatId, InputMedia.photo('https://example.com/image.jpg'))
キーボード
import { BotKeyboard } from '@mtcute/node'
// Inline keyboard
await tg.sendText(chatId, 'Pick one:', {
replyMarkup: BotKeyboard.inline([
[BotKeyboard.callback('Yes', 'btn_yes'), BotKeyboard.callback('No', 'btn_no')],
[BotKeyboard.url('Docs', 'https://mtcute.dev')],
]),
})
// Reply keyboard
await tg.sendText(chatId, 'Choose:', {
replyMarkup: BotKeyboard.reply([
[BotKeyboard.text('Option A'), BotKeyboard.text('Option B')],
]),
})
ページネーション/反復処理
多くのメソッドには、AsyncIterableIterator を返す iter* の対応メソッドがあります。
// Iterate over chat history
for await (const msg of tg.iterHistory(chatId, { chunkSize: 100 })) {
console.log(msg.text)
}
// Iterate over search results
for await (const msg of tg.iterSearchMessages({ query: 'hello', chatId })) {
console.log(msg.id)
}
// Non-iter methods return paginated results with a `.next` cursor
const page = await tg.getHistory(chatId, { limit: 50 })
const nextPage = await tg.getHistory(chatId, { limit: 50, offset: page.next })
クライアントイベント
クライアントは、接続のライフサイクルやエラー用に Emitter インスタンスを公開しています。.add() で登録し、.remove() で登録を解除します。
// Connection state: 'offline' | 'connecting' | 'updating' | 'connected'
// 'updating' means connected but catching up on missed updates
tg.onConnectionState.add((state) => {
console.log('Connection:', state)
})
// Unhandled errors (if no listener, errors are logged to console)
tg.onError.add((err) => {
console.error('Error:', err)
})
// Raw TL updates (before dispatcher processing)
tg.onRawUpdate.add((update) => { ... })
プロキシ/カスタムトランスポート(Node.js)
import { TelegramClient } from '@mtcute/node'
import {
HttpProxyTcpTransport,
SocksProxyTcpTransport,
MtProxyTcpTransport,
proxyTransportFromUrl,
} from '@mtcute/node'
const tg = new TelegramClient({
// or parse from URL (socks4/5, http, https, mtproto):
transport: proxyTransportFromUrl('socks5://user:[email protected]:1080'),
})
さらに読む
完全なドキュメントとLLM向けのリファレンス:https://mtcute.dev/llms.txt。
Context7 MCP が利用できる場合は、ドキュメントを手動で取得する代わりに、そちらを優先して使用してください。ライブラリ ID は /mtcute/mtcute です。