> 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/ko/gaebal/goseup/paen-token-telegram-allim.md).

# Fan Token 전송 Telegram 알림 받기

Chiliz Chain에서 발생하는 Fan Token™ 전송을 모니터링하는 것은 고액 이동에 대한 정보를 유지하고 커뮤니티를 최신 상태로 유지하는 좋은 방법입니다.

약간의 설정과 코드로 Fan Token™ 전송이 특정 임계값을 초과할 때마다 그룹에 알리는 Telegram 봇을 설정할 수 있습니다.

## Envio를 사용하는 방법

[Envio](https://envio.dev/)는 개발자가 Chiliz에서 스마트 컨트랙트 이벤트를 수신하고 이벤트에 따라 작업을 수행할 수 있는 강력한 인덱싱 도구입니다.

이 가이드에서는 봇을 설정하고 관련 이벤트를 캡처하여 Telegram 알림을 자동으로 트리거하는 방법을 알아보겠습니다. 이를 통해 주요 전송을 위한 "고래 감시자" 역할을 합니다.

### 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 인덱서 초기화

다음 명령을 실행하여 Envio 인덱서를 초기화하고 프롬프트에 따라 Chiliz Chain(EVM 호환 블록체인)에서 ERC20 템플릿을 생성합니다.

```bash
pnpx envio init
```

프롬프트가 표시될 때 선택해야 하는 항목들입니다.

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

### 3단계: `config.yaml` 설정

`config.yaml` 파일을 수정하여 FC Barcelona Fan Token™(또는 추적하려는 다른 Fan Token™)의 컨트랙트 주소를 지정합니다.

{% 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!   # 계정 주소
  balance: BigInt! # 토큰 계정 잔액
}
```

이 시점에서 이벤트를 수신하는 ERC20 인덱서가 있습니다.

이제 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단계: 최종 설정 및 인덱서 실행

#### `.env` 파일 설정

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

Telegram 봇 자격 증명으로 `.env`를 편집합니다.

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

#### Telegram 봇 생성

1. Telegram에서 `@BotFather`에 메시지를 보내고 실행합니다.

   ```
   /newbot
   ```
2. 프롬프트에 따라 봇 토큰을 받습니다.
3. 봇을 Telegram 그룹에 추가하고 `/start`를 실행합니다.
4. `https://api.telegram.org/bot<YourBOTToken>/getUpdates`를 방문하여 그룹 채팅 ID를 찾습니다.

{% hint style="success" %}
봇과 함께 새 그룹을 만들었는데 `{"ok":true,"result":[]}`만 표시되면 그룹에서 봇을 제거했다가 다시 추가하세요.
{% endhint %}

#### 마지막으로 의존성을 설치하고 인덱서를 시작합니다.

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

이 설정을 통해 Fan Token 전송을 수신하고 Telegram에 고래 알림을 게시하는 Envio 기반 인덱서를 갖게 됩니다.

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

더 나아가 인덱서를 자체 호스팅하거나 Envio의 호스팅 서비스에 배포할 수 있습니다.

또한 잔액을 저장하고 있으므로 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, and the optional `goal` query parameter:

```
GET https://docs.chiliz.com/ko/gaebal/goseup/paen-token-telegram-allim.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
