> For the complete documentation index, see [llms.txt](https://docs.chiliz.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.chiliz.com/jp/kaihatsu/joukyu/fan-token-telegram-tsuchi.md).

# Fan Token 転送の Telegram 通知を受け取る

Chiliz Chain上で発生するFan Token™の転送を監視することは、高額な動きを把握し、コミュニティに最新情報を共有するための優れた方法です。

少しの設定とコードで、Fan Token™の転送が一定のしきい値を超えるたびにグループに通知するTelegram botを構築できます。

## Envioを使ったやり方は？

[Envio](https://envio.dev/)は、開発者がChiliz上のsmart contractイベントをリッスンし、そのイベントに基づいてアクションを実行できる強力なインデックス作成ツールです。

このハウツーでは、botを設定し、関連するイベントを捕捉して、Telegramアラートを自動的に発火させる方法を紹介します。これにより、大口の転送向けの「クジラ監視（whale watcher）」のような仕組みを構築できます。

### ステップ1: 前提条件のインストール

始める前に、[必要なツール](https://docs.envio.dev/docs/HyperIndex/getting-started#prerequisites)がインストールされていることを確認してください:

* [pnpm](https://pnpm.io/)
* [Node.js](https://nodejs.org/en)
* [Docker](https://www.docker.com/)

{% hint style="info" %}
プロジェクト全体は[こちらのGitHubリポジトリ](https://github.com/DenhamPreen/fc-barce-fan-token-indexer/tree/main)で確認できます。
{% endhint %}

### ステップ2: Envio Indexerの初期化

次のコマンドを実行してEnvio indexerを初期化し、プロンプトに従ってChiliz Chain（EVM互換ブロックチェーン）上にERC20テンプレートを生成します:

```bash
pnpx envio init
```

プロンプトが表示されたら、次のように選択してください:

<figure><img src="/files/22Hm2zNXo9xfisrFiSSN" alt=""><figcaption></figcaption></figure>

### ステップ3: `config.yaml`の設定

`config.yaml`ファイルを編集して、FC BarcelonaのFan Token™（または追跡したい他のFan Token™）のcontractアドレスを指定します:

{% code overflow="wrap" lineNumbers="true" %}

```yaml
# yaml-language-server: $schema=./node_modules/envio/evm.schema.json
name: fan-token-watcher
description: A simple indexer for Fan Tokens that posts notifications to Telegram on large transfers
networks:
  - id: 8888 # Chiliz
    start_block: 0
    contracts:
      - name: ERC20
        address: "0xFD3C73b3B09D418841dd6Aff341b2d6e3abA433b" # FC Barcelona
        handler: src/EventHandlers.ts
        events:          
          - event: "Transfer(address indexed from, address indexed to, uint256 value)"
field_selection:
  transaction_fields:
    - "hash"
```

{% endcode %}

**注意:** 転送のみに関心があるため、`approval`イベントは削除します。

### ステップ4: GraphQLスキーマの簡素化

`schema.graphql`ファイルを編集して、アカウント残高のみを追跡するようにします:

```graphql
type Account {
  id: ID!   # Address of the account
  balance: BigInt! # Account balance of tokens
}
```

この時点で、イベントをリッスンするERC20 indexerができました。

それでは、Telegram通知を投稿するロジックを追加しましょう。

### ステップ5: Telegram通知ロジックの実装

`/src/EventHandlers.ts`ファイルを編集して、大口の転送を検出してTelegramアラートを送信するロジックを追加します。

{% code overflow="wrap" lineNumbers="true" %}

```typescript
import { ERC20 } from "generated";
import { isIndexingAtHead, indexBalances } from "./libs/helpers";
import { fetchEnsHandle } from "./libs/ens";
import { sendMessageToTelegram } from "./libs/telegram";
import { WHALE_THRESHOLD, explorerUrlAddress, explorerUrlTx } from "./constants";

ERC20.Transfer.handler(async ({ event, context }) => {
  if (isIndexingAtHead(event.block.timestamp) && event.params.value >= BigInt(WHALE_THRESHOLD)) {
    const ensHandleOrFromAddress = await fetchEnsHandle(event.params.from); 
    const ensHandleOrToAddress = await fetchEnsHandle(event.params.to);
    const msg = `FC Barcelona WHALE ALERT 🐋: A new transfer has been made by <a href="${explorerUrlAddress(
      event.params.from
    )}">${ensHandleOrFromAddress}</a> to <a href="${explorerUrlAddress(
      event.params.to
    )}">${ensHandleOrToAddress}</a> for ${event.params.value} FC Barcelona! 🔥 - <a href="${explorerUrlTx(
      event.transaction.hash
    )}">transaction</a>`;

    await sendMessageToTelegram(msg);
  }

  await indexBalances(context, event);
});
```

{% endcode %}

{% hint style="success" %}
サンプルの`/libs/`フォルダーは、`helpers.ts`と`ens.ts`ファイルを含めて[こちらのGitHub](https://github.com/DenhamPreen/fc-barce-fan-token-indexer/tree/main/src/libs)で確認できます。
{% endhint %}

### ステップ6: 定数の設定

環境変数を保存するための`constants.ts`ファイルを作成します:

{% code overflow="wrap" lineNumbers="true" %}

```typescript
export const EXPLORER_URL_MONAD = process.env.ENVIO_EXPLORER_URL_MONAD;
export const WHALE_THRESHOLD: string = process.env.ENVIO_WHALE_THRESHOLD ?? "1000";
export const BOT_TOKEN = process.env.ENVIO_BOT_TOKEN;
export const CHANNEL_ID = process.env.ENVIO_TELEGRAM_CHANNEL_ID;
export const MESSAGE_THREAD_ID = process.env.ENVIO_TELEGRAM_MESSAGE_THREAD_ID;

export const explorerUrlAddress = (address: string) =>
  EXPLORER_URL_MONAD + "address/" + address;
export const explorerUrlTx = (txHash: string) =>
  EXPLORER_URL_MONAD + "tx/" + txHash;
```

{% endcode %}

### ステップ7: Telegramメッセージの送信

[Axios HTTPクライアント](https://axios-http.com/)をインストールします:

```bash
pnpm i axios
```

Axiosを使ってメッセージを送信するヘルパー関数を`libs/telegram.ts`に作成します:

{% code overflow="wrap" lineNumbers="true" %}

```typescript
import axios from "axios";
import { CHANNEL_ID, MESSAGE_THREAD_ID, BOT_TOKEN } from "../constants";

export const sendMessageToTelegram = async (message: string): Promise<void> => {
  try {
    const apiUrl = `https://api.telegram.org/bot${BOT_TOKEN}/sendMessage`;
    await axios.post(apiUrl, {
      chat_id: CHANNEL_ID,
      text: message,
      parse_mode: "HTML",
    });
  } catch (error) {
    console.error("Error sending message:", error);
  }
};
```

{% endcode %}

### ステップ8: 最終設定とIndexerの実行

#### `.env`ファイルの設定

```sh
cp .env.example .env
```

`.env`をTelegram bot認証情報で編集します:

```sh
ENVIO_BOT_TOKEN=
ENVIO_TELEGRAM_CHANNEL_ID=
ENVIO_TELEGRAM_MESSAGE_THREAD_ID=
ENVIO_EXPLORER_URL="https://chiliscan.com/"
ENVIO_WHALE_THRESHOLD=1000
```

#### Telegram botの作成

1. Telegramで`@BotFather`にメッセージを送り、次を実行します:

   ```
   /newbot
   ```
2. プロンプトに従ってbotトークンを取得します。
3. botをTelegramグループに追加し、`/start`を実行します。
4. `https://api.telegram.org/bot<YourBOTToken>/getUpdates`にアクセスして、グループのチャットIDを確認します。

{% hint style="success" %}
botと一緒に新しいグループを作成したのに`{"ok":true,"result":[]}`しか返ってこない場合は、botをグループから削除して再度追加してください。
{% endhint %}

#### 最後に、依存関係をインストールしてindexerを起動します

```sh
pnpm i
pnpm envio dev
```

この設定により、Fan Tokenの転送をリッスンし、クジラアラートをTelegramに投稿するEnvio駆動のindexerができました。

<figure><img src="/files/xAdCGyuNlmYiJYeZWwvN" alt=""><figcaption></figcaption></figure>

さらに進めるには、indexerをセルフホストするか、Envioのホスティングサービスにdeployできます。

また、残高を保存しているため、GraphQLの残高APIとしても利用できます。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.chiliz.com/jp/kaihatsu/joukyu/fan-token-telegram-tsuchi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
