You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
45
45
46
46
The directory should look like this:
47
47
```
@@ -52,10 +52,10 @@ my_bot
52
52
└── ton.py
53
53
```
54
54
55
-
Now let's begin writing code!
55
+
Now, let’s start coding!
56
56
57
57
## 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.
59
59
60
60
**config.py**
61
61
```python
@@ -71,16 +71,17 @@ else:
71
71
```
72
72
73
73
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).
77
77
78
78
You can also choose whether your bot will run on the testnet or the mainnet (4th line).
79
79
80
-
That's all for the Config file, so we can move forward!
80
+
Once these values are set, we can move forward!
81
+
81
82
82
83
## 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.
84
85
85
86
Import the sqlite3 library.
86
87
```python
@@ -93,7 +94,7 @@ con = sqlite3.connect('db.sqlite')
93
94
cur = con.cursor()
94
95
```
95
96
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.
97
98
```python
98
99
cur.execute('''CREATE TABLE IF NOT EXISTS Users (
99
100
uid INTEGER,
@@ -102,7 +103,7 @@ cur.execute('''CREATE TABLE IF NOT EXISTS Users (
102
103
con.commit()
103
104
```
104
105
105
-
Now we need to declare a few functions to work with the database.
106
+
Define helper functions to interact with the database:
106
107
107
108
`add_user` function will be used to insert new users into the database.
108
109
```python
@@ -139,24 +140,23 @@ def get_balance(uid):
139
140
140
141
And that's all for the `db.py` file!
141
142
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
+
143
145
144
146
## TON Center API
145
147
In the `ton.py` file we'll declare a function that will process all new deposits, increase user balances, and notify users.
146
148
147
149
### getTransactions method
148
150
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:
150
152
https://toncenter.com/api/v2/
151
153
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.
155
156
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.
159
158
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.
160
160
```json
161
161
{
162
162
"ok": true,
@@ -205,15 +205,13 @@ Well, so the `ok` field is set to `true` when everything is good, and we have an
205
205
}
206
206
```
207
207
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.
211
209
212
-
Now we're ready to create a payment handler.
210
+
Now, we're ready to create a payment handler.
213
211
214
212
### Sending API requests from code
215
213
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.
217
215
```python
218
216
import requests
219
217
import asyncio
@@ -227,16 +225,15 @@ import config
227
225
import db
228
226
```
229
227
230
-
Let's think about how payment processing can be implemented.
228
+
Let's explore how payment processing can be implemented.
231
229
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.
233
231
234
-
For that we need to know what the last processed transaction was. The simplest approach would be to just save info about that transactionin 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.
235
233
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.
238
235
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 iteasier to work with async functions.
240
237
241
238
This is what our `start` function should look like:
242
239
```python
@@ -257,7 +254,7 @@ async def start():
257
254
...
258
255
```
259
256
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..
261
258
```python
262
259
whileTrue:
263
260
# 2 Seconds delay between checks
@@ -275,9 +272,9 @@ while True:
275
272
...
276
273
```
277
274
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.
279
276
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.
281
278
282
279
```python
283
280
whileTrue:
@@ -298,12 +295,12 @@ while True:
298
295
...
299
296
```
300
297
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
304
301
- notify the user about their deposit
305
302
306
-
Here is the code that will do all of that:
303
+
Below is the code that handles this:
307
304
308
305
```python
309
306
whileTrue:
@@ -332,21 +329,20 @@ while True:
332
329
parse_mode=ParseMode.MARKDOWN)
333
330
```
334
331
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:
338
333
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.
340
335
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.
342
337
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.
344
339
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.
345
341
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:
346
342
`{value / 1e9:.2f}`
347
343
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.
348
344
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.
350
346
351
347
It's simple:
352
348
```python
@@ -369,7 +365,7 @@ Our bot is now 3/4 done; we only need to create a user interface with a few butt
369
365
370
366
### Initialization
371
367
372
-
Open the `bot.py` file and import all the modules we need.
368
+
Open the `bot.py` file and import all necessary modules.
373
369
```python
374
370
# Logging module
375
371
import logging
@@ -392,21 +388,21 @@ Let's set up logging to our program so that we can see what happens later for de
392
388
logging.basicConfig(level=logging.INFO)
393
389
```
394
390
395
-
Now we need to initialize the bot object and its dispatcher with Aiogram.
391
+
Next, we initialize the bot and dispatcher using Aiogram:
396
392
```python
397
393
bot = Bot(token=config.BOT_TOKEN)
398
394
dp = Dispatcher(bot)
399
395
```
400
396
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.
402
398
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.
404
400
405
401
### Message handlers
406
402
407
403
#### /start Command
408
404
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.
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`.
436
432
437
433
#### Balance button
438
434
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.
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.
489
484
490
485
### Bot start
491
486
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`.
493
488
494
489
```python
495
490
if__name__=='__main__':
@@ -503,9 +498,9 @@ if __name__ == '__main__':
503
498
ex.start_polling()
504
499
```
505
500
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:
507
502
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.
0 commit comments