Skip to content

Commit cc43a5c

Browse files
authored
Merge pull request #31 from D-Shestak/patch-6
Patch 6
2 parents 867a5e9 + dd0818f commit cc43a5c

File tree

1 file changed

+59
-64
lines changed

1 file changed

+59
-64
lines changed

docs/v3/guidelines/dapps/tutorials/telegram-bot-examples/accept-payments-in-a-telegram-bot-2.md

Lines changed: 59 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ The bot will look like this:
1515

1616
### Source code
1717

18-
Sources are available on GitHub:
18+
The sources are available on GitHub:
1919
* https://github.com/Gusarich/ton-bot-example
2020

2121
## 📖 What you'll learn
@@ -25,9 +25,9 @@ You'll learn how to:
2525
- work with public TON API
2626

2727
## ✍️ What you need to get started
28-
Install [Python](https://www.python.org/) if you haven't yet.
28+
Install [Python](https://www.python.org/) if you haven't already.
2929

30-
Also you need these PyPi libraries:
30+
Install the required PyPi libraries:
3131
- aiogram
3232
- requests
3333

@@ -38,10 +38,10 @@ pip install aiogram==2.21 requests
3838

3939
## 🚀 Let's get started!
4040
Create a directory for our bot with four files in it:
41-
- `bot.py`—program to run a Telegram bot
42-
- `config.py`config file
43-
- `db.py`—module to interact with the sqlite3 database
44-
- `ton.py`module to handle payments in TON
41+
- `bot.py` program to run the Telegram bot
42+
- `config.py` configuration file
43+
- `db.py` module for interacting with the SQLite database
44+
- `ton.py`Module for handling payments in TON
4545

4646
The directory should look like this:
4747
```
@@ -52,10 +52,10 @@ my_bot
5252
└── ton.py
5353
```
5454

55-
Now let's begin writing code!
55+
Now, let’s start coding!
5656

5757
## Config
58-
Let's start with `config.py` because it is the smallest one. We just need to set a few parameters in it.
58+
We'll begin with `config.py` since it's the smallest file. We just need to set a few parameters in it.
5959

6060
**config.py**
6161
```python
@@ -71,16 +71,17 @@ else:
7171
```
7272

7373
Here you need to fill in the values in the first three lines:
74-
- `BOT_TOKEN` is your Telegram Bot token which you can get after [creating a bot](https://t.me/BotFather).
75-
- `DEPOSIT_ADDRESS` is your project's wallet address which will accept all payments. You can just create a new TON Wallet and copy its address.
76-
- `API_KEY` is your API key from TON Center which you can get in [this bot](https://t.me/tonapibot).
74+
- `BOT_TOKEN`- Your Telegram bot token [creating a bot](https://t.me/BotFather).
75+
- `DEPOSIT_ADDRESS` - Your project's wallet address for receiving payments. You can create a new TON Wallet and copy its address.
76+
- `API_KEY` - Your API key from TON Center which you can get in [this bot](https://t.me/tonapibot).
7777

7878
You can also choose whether your bot will run on the testnet or the mainnet (4th line).
7979

80-
That's all for the Config file, so we can move forward!
80+
Once these values are set, we can move forward!
81+
8182

8283
## Database
83-
Now let's edit the `db.py` file that will work with the database of our bot.
84+
Now let's edit the `db.py` file to store user balances.
8485

8586
Import the sqlite3 library.
8687
```python
@@ -93,7 +94,7 @@ con = sqlite3.connect('db.sqlite')
9394
cur = con.cursor()
9495
```
9596

96-
To store information about users (their balances in our case), create a table called "Users" with User ID and balance rows.
97+
To store information about users (their balances). Create a table called **Users** with User id and balance columns.
9798
```python
9899
cur.execute('''CREATE TABLE IF NOT EXISTS Users (
99100
uid INTEGER,
@@ -102,7 +103,7 @@ cur.execute('''CREATE TABLE IF NOT EXISTS Users (
102103
con.commit()
103104
```
104105

105-
Now we need to declare a few functions to work with the database.
106+
Define helper functions to interact with the database:
106107

107108
`add_user` function will be used to insert new users into the database.
108109
```python
@@ -139,24 +140,23 @@ def get_balance(uid):
139140

140141
And that's all for the `db.py` file!
141142

142-
Now we can use these four functions in other components of the bot to work with the database.
143+
Once this file is set up, we can use these functions in other parts of the bot.
144+
143145

144146
## TON Center API
145147
In the `ton.py` file we'll declare a function that will process all new deposits, increase user balances, and notify users.
146148

147149
### getTransactions method
148150

149-
We'll use the TON Center API. Their docs are available here:
151+
We'll use the TON Center API. Their documentation is available here:
150152
https://toncenter.com/api/v2/
151153

152-
We need the [getTransactions](https://toncenter.com/api/v2/#/accounts/get_transactions_getTransactions_get) method to get information about latest transactions of a given account.
153-
154-
Let's have a look at what this method takes as input parameters and what it returns.
154+
We need the [getTransactions](https://toncenter.com/api/v2/#/accounts/get_transactions_getTransactions_get) method to retrieve information about the latest transactions of a given account.
155+
Let's review the input parameters this method requires and what it returns.
155156

156-
There is only one mandatory input field `address`, but we also need the `limit` field to specify how many transactions we want to get in return.
157-
158-
Now let's try to run this method on the [TON Center website](https://toncenter.com/api/v2/#/accounts/get_transactions_getTransactions_get) with any existing wallet address to understand what we should get from the output.
157+
The only mandatory input field is `address`, but we also need the `limit` field to specify how many transactions we want to retrieve.
159158

159+
Let's test this method on the [TON Center website](https://toncenter.com/api/v2/#/accounts/get_transactions_getTransactions_get) website using any existing wallet address to see what the output looks like.
160160
```json
161161
{
162162
"ok": true,
@@ -205,15 +205,13 @@ Well, so the `ok` field is set to `true` when everything is good, and we have an
205205
}
206206
```
207207

208-
We can see that information that can help us identify the exact transaction is stored in `transaction_id` field. We need the `lt` field from it to understand which transaction happened earlier and which happened later.
209-
210-
The information about the coin transfer is in the `in_msg` field. We'll need `value` and `message` from it.
208+
We can see that the key details for identifying a specific transaction are stored in the `transaction_id` field. We need the `lt` field from this to determine the chronological order of transactions.
211209

212-
Now we're ready to create a payment handler.
210+
Now, we're ready to create a payment handler.
213211

214212
### Sending API requests from code
215213

216-
Let's begin with importing the required libraries and our two previous files: `config.py` and `db.py`.
214+
Let's start by importing the required libraries along with the`config.py` and `db.py` files.
217215
```python
218216
import requests
219217
import asyncio
@@ -227,16 +225,15 @@ import config
227225
import db
228226
```
229227

230-
Let's think about how payment processing can be implemented.
228+
Let's explore how payment processing can be implemented.
231229

232-
We can call the API every few seconds and check if there are any new transactions to our wallet address.
230+
We can call the API every few seconds to check if new transactions have been received in our wallet.
233231

234-
For that we need to know what the last processed transaction was. The simplest approach would be to just save info about that transaction in some file and update it every time we process a new transaction.
232+
To do this, we need to track the last processed transaction. The simplest approach is to save this transaction’s details in a file and update it every time a new transaction is processed.
235233

236-
What information about the transaction will we store in the file? Actually, we only need to store the `lt` value—logical time.
237-
With that value we'll be able to understand what transactions we need to process.
234+
What information should we store? We only need the `lt` (logical time) value, which will allow us to determine which transactions need to be processed.
238235

239-
So we need to define a new async function; let's call it `start`. Why does this function need to be asynchronous? That is because the Aiogram library for Telegram bots is also asynchronous, and it'll be easier to work with async functions later.
236+
Next, we define an asynchronous function called `start`. Why async? Because the Aiogram library for Telegram bots is asynchronous, making it easier to work with async functions.
240237

241238
This is what our `start` function should look like:
242239
```python
@@ -257,7 +254,7 @@ async def start():
257254
...
258255
```
259256

260-
Now let's write the body of while loop. We need to call TON Center API there every few seconds.
257+
Within the `while` loop, we need to call the TON Center API every few seconds..
261258
```python
262259
while True:
263260
# 2 Seconds delay between checks
@@ -275,9 +272,9 @@ while True:
275272
...
276273
```
277274

278-
After the call with `requests.get`, we have a variable `resp` that contains the response from the API. `resp` is an object and `resp['result']` is a list with the last 100 transactions for our address.
275+
After making a `requests.get` call, the response is stored in the `resp` variable. The resp object contains a result list with the 100 most recent transactions for our address.
279276

280-
Now let's just iterate over these transactions and find the new ones.
277+
Now, we iterate through these transactions and identify the new ones.
281278

282279
```python
283280
while True:
@@ -298,12 +295,12 @@ while True:
298295
...
299296
```
300297

301-
How do we process a new transaction? We need to:
302-
- understand which user sent it
303-
- increase that user's balance
298+
How to process a new transaction? We need to:
299+
- dientify which user sent the transaction
300+
- update that user's balance
304301
- notify the user about their deposit
305302

306-
Here is the code that will do all of that:
303+
Below is the code that handles this:
307304

308305
```python
309306
while True:
@@ -332,21 +329,20 @@ while True:
332329
parse_mode=ParseMode.MARKDOWN)
333330
```
334331

335-
Let's have a look at it and understand what it does.
336-
337-
All the information about the coin transfer is in `tx['in_msg']`. We just need the 'value' and 'message' fields from it.
332+
Let's analyze what it does:
338333

339-
First of all, we check if the value is greater than zero and only continue if it is.
334+
All the information about the coin transfer is in `tx['in_msg']`. We just need the 'value' and 'message' fields.
340335

341-
Then we expect the transfer to have a comment ( `tx['in_msg']['message']` ), to have a user ID from our bot, so we verify if it is a valid number and if that UID exists in our database.
336+
First, we check if value is greater than zero—if not, we ignore the transaction.
342337

343-
After these simple checks, we have a variable `value` with the deposit amount, and a variable `uid` with the ID of the user that made this deposit. So we can just add funds to their account and send a notification message.
338+
Next, we verify that the ( `tx['in_msg']['message']` ) field contains a valid user ID from our bot and that the UID exists in our database.
344339

340+
After these checks, we extract the deposit amount `value` and the user ID `uid`. Then, we add the funds to the user’s account and send them a notification.
345341
Also note that value is in nanotons by default, so we need to divide it by 1 billion. We do that in line with notification:
346342
`{value / 1e9:.2f}`
347343
Here we divide the value by `1e9` (1 billion) and leave only two digits after the decimal point to show it to the user in a friendly format.
348344

349-
Great! The program can now process new transactions and notify users about deposits. But we should not forget about storing `lt` that we have used before. We must update the last `lt` because a newer transaction was processed.
345+
Once a transaction is processed, we must update the stored `lt` value to reflect the most recent transaction.
350346

351347
It's simple:
352348
```python
@@ -369,7 +365,7 @@ Our bot is now 3/4 done; we only need to create a user interface with a few butt
369365

370366
### Initialization
371367

372-
Open the `bot.py` file and import all the modules we need.
368+
Open the `bot.py` file and import all necessary modules.
373369
```python
374370
# Logging module
375371
import logging
@@ -392,21 +388,21 @@ Let's set up logging to our program so that we can see what happens later for de
392388
logging.basicConfig(level=logging.INFO)
393389
```
394390

395-
Now we need to initialize the bot object and its dispatcher with Aiogram.
391+
Next, we initialize the bot and dispatcher using Aiogram:
396392
```python
397393
bot = Bot(token=config.BOT_TOKEN)
398394
dp = Dispatcher(bot)
399395
```
400396

401-
Here we use `BOT_TOKEN` from our config that we made at the beginning of the tutorial.
397+
Here we use the `BOT_TOKEN` from our config file.
402398

403-
We initialized the bot but it's still empty. We must add some functions for interaction with the user.
399+
At this point, our bot is initialized but still lacks functionality. We now need to define interaction handlers.
404400

405401
### Message handlers
406402

407403
#### /start Command
408404

409-
Let's begin with the `/start` and `/help` commands handler. This function will be called when the user launches the bot for the first time, restarts it, or uses the `/help` command.
405+
Let's begin with the `/start` and `/help` commands handlers. This function will be triggered when the user launches the bot for the first time, restarts it, or uses the `/help` command.
410406

411407
```python
412408
@dp.message_handler(commands=['start', 'help'])
@@ -432,13 +428,13 @@ async def welcome_handler(message: types.Message):
432428
parse_mode=ParseMode.MARKDOWN)
433429
```
434430

435-
The welcome message can be anything you want. Keyboard buttons can be any text, but in this example they are labeled in the most clear way for our bot: `Deposit` and `Balance`.
431+
The welcome message can be customized to anything you prefer. The keyboard buttons can also be labeled as needed, but in this example, we use the most straightforward labels for our bot: `Deposit` and `Balance`.
436432

437433
#### Balance button
438434

439-
Now the user can start the bot and see the keyboard with two buttons. But after calling one of these, the user won't get any response because we didn't create any function for them.
435+
Once the user starts the bot, they will see a keyboard with two buttons. However, pressing these buttons won't yield any response yet, as we haven't created functions for them.
440436

441-
So let's add a function to request a balance.
437+
Let's add a function to check the user's balance.
442438

443439
```python
444440
@dp.message_handler(commands='balance')
@@ -455,11 +451,11 @@ async def balance_handler(message: types.Message):
455451
parse_mode=ParseMode.MARKDOWN)
456452
```
457453

458-
It's pretty simple. We just get the balance from the database and send the message to the user.
454+
The implementation is simple: we retrieve the balance from the database and send a message displaying it to the user.
459455

460456
#### Deposit button
461457

462-
And what about the second `Deposit` button? Here is the function for it:
458+
Let's implement the `Deposit` button. Here’s how it works:
463459

464460
```python
465461
@dp.message_handler(commands='deposit')
@@ -483,13 +479,12 @@ async def deposit_handler(message: types.Message):
483479
parse_mode=ParseMode.MARKDOWN)
484480
```
485481

486-
What we do here is also easy to understand.
487482

488-
Remember when in the `ton.py` file we were determining which user made a deposit by commenting with their UID? Now here in the bot we need to ask the user to send a transaction with a comment containing their UID.
483+
This step is crucial because, in `ton.py` we identify which user made a deposit by extracting their UID from the transaction comment. Now, within the bot, we must guide the user to include their UID in the transaction comment.
489484

490485
### Bot start
491486

492-
The only thing we have to do now in `bot.py` is to launch the bot itself and also run the `start` function from `ton.py`.
487+
The final step in `bot.py` is to launch the bot and also start the `start` function from `ton.py`.
493488

494489
```python
495490
if __name__ == '__main__':
@@ -503,9 +498,9 @@ if __name__ == '__main__':
503498
ex.start_polling()
504499
```
505500

506-
At this moment, we have written all the required code for our bot. If you did everything correctly, it must work when you run it with `python my-bot/bot.py` command in the terminal.
501+
At this point, we have written all the necessary code for our bot. If everything is set up correctly, the bot should work when you run the following command in the terminal:
507502

508-
If your bot doesn't work correctly, compare your code with code [from this repository](https://github.com/Gusarich/ton-bot-example).
503+
If the bot does not function as expected, compare your code with the code [from this repository](https://github.com/Gusarich/ton-bot-example) to ensure there are no discrepancies.
509504

510505
## References
511506

0 commit comments

Comments
 (0)