> 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/pl/tworzenie/zaawansowane/powiadomienia-telegram.md).

# Powiadomienia Telegram o transferach

Monitorowanie transferów Fan Tokens na Chiliz Chain to świetny sposób na śledzenie ruchów o wysokiej wartości i informowanie społeczności.

Przy odrobinie konfiguracji i kodu możesz skonfigurować bota Telegram, który powiadomi grupę za każdym razem, gdy transfer Fan Tokena przekroczy określony próg.

## Jak to zrobić za pomocą Envio?

[Envio](https://envio.dev/) to potężne narzędzie indeksowania, które pozwala deweloperom nasłuchiwać zdarzeń smart kontraktów na Chiliz i podejmować działania na podstawie zdarzenia.

W tym poradniku zobaczysz, jak skonfigurować bota, przechwytywać odpowiednie zdarzenia i automatycznie wyzwalać alerty Telegram, zamieniając konfigurację w "strażnika wielorybów" dla dużych transferów.

### Krok 1: Zainstaluj wymagania wstępne

Zanim zaczniesz, upewnij się, że masz zainstalowane [wymagane narzędzia](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" %}
Pełny projekt znajdziesz [w tym repozytorium GitHub](https://github.com/DenhamPreen/fc-barce-fan-token-indexer/tree/main).
{% endhint %}

### Krok 2: Zainicjuj indekser Envio

Uruchom następujące polecenie, aby zainicjować indekser Envio i postępuj zgodnie z promptami, aby wygenerować szablon ERC20 na Chiliz Chain (która jest blockchainem kompatybilnym z EVM):

```bash
pnpx envio init
```

Oto wybory, które powinieneś dokonać po wyświetleniu promptów:

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

### Krok 3: Skonfiguruj `config.yaml`

Zmodyfikuj plik `config.yaml`, aby określić adres kontraktu Fan Tokena FC Barcelona (lub dowolnego innego Fan Tokena, który chcesz śledzić):

{% 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 %}

**Uwaga:** Usuwamy zdarzenie `approval`, ponieważ interesują nas tylko transfery.

### Krok 4: Uprość schemat GraphQL

Zmodyfikuj plik `schema.graphql`, aby śledzić tylko salda kont:

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

W tym miejscu mamy indekser ERC20, który nasłuchuje zdarzeń.

Teraz dodajmy logikę do wysyłania powiadomień Telegram.

### Krok 5: Zaimplementuj logikę powiadomień Telegram

Zmodyfikuj plik `/src/EventHandlers.ts`, aby zawierał logikę wykrywania dużych transferów i wysyłania alertów 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" %}
Przykładowy folder `/libs/` znajdziesz [tutaj na GitHub](https://github.com/DenhamPreen/fc-barce-fan-token-indexer/tree/main/src/libs), w tym pliki `helpers.ts` i `ens.ts`.
{% endhint %}

### Krok 6: Skonfiguruj stałe

Utwórz plik `constants.ts` do przechowywania zmiennych środowiskowych:

{% 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 %}

### Krok 7: Wysyłanie wiadomości Telegram

Zainstaluj [klienta HTTP Axios](https://axios-http.com/):

```bash
pnpm i axios
```

Utwórz funkcję pomocniczą w `libs/telegram.ts` do wysyłania wiadomości za pomocą Axios:

{% 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 %}

### Krok 8: Finalna konfiguracja i uruchomienie indeksera

#### Skonfiguruj plik `.env`

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

Edytuj `.env` z danymi uwierzytelniającymi bota Telegram:

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

#### Utwórz bota Telegram

1. Wyślij wiadomość do `@BotFather` na Telegram i uruchom:

   ```
   /newbot
   ```
2. Postępuj zgodnie z promptami, aby uzyskać token bota.
3. Dodaj bota do grupy Telegram i uruchom `/start`.
4. Odwiedź `https://api.telegram.org/bot<YourBOTToken>/getUpdates`, aby znaleźć ID czatu grupy.

{% hint style="success" %}
Jeśli stworzyłeś nową grupę z botem i dostajesz tylko `{"ok":true,"result":[]}`, usuń bota z grupy i dodaj go ponownie.
{% endhint %}

#### Na koniec, zainstaluj zależności i uruchom indekser

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

Dzięki tej konfiguracji masz teraz indekser oparty na Envio, który nasłuchuje transferów Fan Tokens i wysyła alerty o wielorybach do Telegrama.

<figure><img src="/files/6TtbbzTNqGKM0yIBpIZJ" alt=""><figcaption></figcaption></figure>

Idąc dalej, możesz samodzielnie hostować indekser lub wdrożyć go do usługi hostowanej Envio.

Ponieważ zapisujemy salda, może być też używany jako API sald GraphQL.


---

# 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/pl/tworzenie/zaawansowane/powiadomienia-telegram.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.
