salogram-bot 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- salogram_bot-1.0.0/PKG-INFO +154 -0
- salogram_bot-1.0.0/README.md +142 -0
- salogram_bot-1.0.0/pyproject.toml +20 -0
- salogram_bot-1.0.0/salobot.py +444 -0
- salogram_bot-1.0.0/salogram_bot.egg-info/PKG-INFO +154 -0
- salogram_bot-1.0.0/salogram_bot.egg-info/SOURCES.txt +7 -0
- salogram_bot-1.0.0/salogram_bot.egg-info/dependency_links.txt +1 -0
- salogram_bot-1.0.0/salogram_bot.egg-info/top_level.txt +1 -0
- salogram_bot-1.0.0/setup.cfg +4 -0
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: salogram-bot
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Official Python SDK for building bots on Salogram
|
|
5
|
+
Author: Salogram Developers
|
|
6
|
+
Keywords: salogram,bot,sdk,chatbot
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Requires-Python: >=3.9
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# Salogram Bot SDK for Python
|
|
14
|
+
|
|
15
|
+
Salogram botlarini oddiy Python orqali yaratish uchun rasmiy kutubxona. Bot dasturi dasturchining o‘z kompyuteri yoki serverida ishlaydi va Salogram bilan HTTPS orqali muloqot qiladi. Kutubxona Python standart kutubxonasidan foydalanadi — `requests` yoki boshqa qo‘shimcha paket talab qilinmaydi.
|
|
16
|
+
|
|
17
|
+
## O‘rnatish
|
|
18
|
+
|
|
19
|
+
ZIP arxivni oching, terminalda `salogram-bot-sdk` papkasiga kiring va:
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
python -m pip install .
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Kutubxona hali PyPI'ga chiqarilmagan. Shu sababli `pip install salogram-bot` global PyPI buyrug‘i hozircha ishlamasligi mumkin; yuqoridagi lokal o‘rnatish usulidan foydalaning.
|
|
26
|
+
|
|
27
|
+
## Token olish
|
|
28
|
+
|
|
29
|
+
1. Salogram akkauntingizga kiring.
|
|
30
|
+
2. Bot Studio'ni oching va kerakli botni tanlang.
|
|
31
|
+
3. **Sozlamalar → Python SDK · API token → Token yaratish** ni bosing.
|
|
32
|
+
4. Tokenni nusxalab, o‘z dasturingizdagi xavfsiz muhit o‘zgaruvchisida saqlang.
|
|
33
|
+
5. Token sahifadan chiqilgach qayta ko‘rsatilmaydi. Yo‘qolsa, Bot Studio'dan yangisini yarating. Yangisini yaratish eskisini bekor qiladi.
|
|
34
|
+
|
|
35
|
+
## Birinchi bot
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
import os
|
|
39
|
+
from salobot import Bot
|
|
40
|
+
|
|
41
|
+
bot = Bot(
|
|
42
|
+
token=os.environ["SALOGRAM_BOT_TOKEN"],
|
|
43
|
+
base_url="https://salogram.pythonanywhere.com",
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
@bot.command("start")
|
|
47
|
+
async def start(ctx):
|
|
48
|
+
await ctx.reply(f"Salom, {ctx.user.name}! Men Python orqali ishlaydigan SaloBotman.")
|
|
49
|
+
|
|
50
|
+
@bot.command("help")
|
|
51
|
+
async def help_command(ctx):
|
|
52
|
+
await ctx.reply("Mavjud buyruqlar: /start, /help")
|
|
53
|
+
|
|
54
|
+
@bot.on_message()
|
|
55
|
+
async def echo(ctx):
|
|
56
|
+
if ctx.text and not ctx.text.startswith("/"):
|
|
57
|
+
await ctx.reply("Siz yozdingiz: " + ctx.text)
|
|
58
|
+
|
|
59
|
+
bot.run()
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Windows PowerShell'da tokenni vaqtincha belgilash:
|
|
63
|
+
|
|
64
|
+
```powershell
|
|
65
|
+
$env:SALOGRAM_BOT_TOKEN="sbot_your_token_here"
|
|
66
|
+
python bot.py
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Tugmalar va callback
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
from salobot import Bot, Button
|
|
73
|
+
|
|
74
|
+
bot = Bot(token="sbot_...", base_url="https://salogram.pythonanywhere.com")
|
|
75
|
+
|
|
76
|
+
@bot.command("start")
|
|
77
|
+
async def start(ctx):
|
|
78
|
+
await ctx.reply("Bo‘limni tanlang:", buttons=[
|
|
79
|
+
Button("Yangiliklar", "news"),
|
|
80
|
+
Button("Yordam", "help"),
|
|
81
|
+
])
|
|
82
|
+
|
|
83
|
+
@bot.on_callback()
|
|
84
|
+
async def on_button(ctx):
|
|
85
|
+
if ctx.callback == "news":
|
|
86
|
+
await ctx.reply("Salogram yangiliklari!")
|
|
87
|
+
elif ctx.callback == "help":
|
|
88
|
+
await ctx.reply("Yordam uchun /help buyrug‘ini yuboring.")
|
|
89
|
+
|
|
90
|
+
bot.run()
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## Fayllar yuborish
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
@bot.command("photo")
|
|
97
|
+
async def photo(ctx):
|
|
98
|
+
await ctx.reply_photo("rasm.jpg", caption="Salomogramdan rasm")
|
|
99
|
+
|
|
100
|
+
@bot.command("file")
|
|
101
|
+
async def file(ctx):
|
|
102
|
+
await ctx.reply_file("document.pdf", caption="Hujjat")
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
`send_video()` va `send_audio()` metodlari ham mavjud. Fayllar botning Salogram storage kvotasiga saqlanadi.
|
|
106
|
+
|
|
107
|
+
## Doimiy xotira
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
@bot.command("remember")
|
|
111
|
+
async def remember(ctx):
|
|
112
|
+
await bot.set_user_data(ctx.user.id, "favorite_color", "green")
|
|
113
|
+
await ctx.reply("Saqladim!")
|
|
114
|
+
|
|
115
|
+
@bot.command("color")
|
|
116
|
+
async def color(ctx):
|
|
117
|
+
value = await bot.get_user_data(ctx.user.id, "favorite_color", "noma'lum")
|
|
118
|
+
await ctx.reply("Sevimli rang: " + str(value))
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Umumiy bot xotirasi uchun `set_data()`, `get_data()` va `delete_data()` ishlatiladi.
|
|
122
|
+
|
|
123
|
+
## Qo‘llab-quvvatlanadigan imkoniyatlar
|
|
124
|
+
|
|
125
|
+
- `@bot.command("name")` — buyruqlar.
|
|
126
|
+
- `@bot.on_message()` — oddiy xabarlar.
|
|
127
|
+
- `@bot.on_callback()` — inline tugma callback hodisalari.
|
|
128
|
+
- `ctx.reply()` — xabar yuborish.
|
|
129
|
+
- `ctx.reply_photo()`, `ctx.reply_file()` — media/fayl yuborish.
|
|
130
|
+
- `bot.send_video()`, `bot.send_audio()`, `bot.send_document()` — video, audio va hujjat.
|
|
131
|
+
- `bot.get_me()` — bot profilini olish.
|
|
132
|
+
- `bot.set_data()/get_data()/delete_data()` — umumiy saqlash.
|
|
133
|
+
- `bot.set_user_data()/get_user_data()/delete_user_data()` — foydalanuvchiga tegishli xotira.
|
|
134
|
+
- Botning chatdagi xabarlari va fayllari Salogram'da ko‘rinadi.
|
|
135
|
+
|
|
136
|
+
## Muhim qoidalar
|
|
137
|
+
|
|
138
|
+
- Bot foydalanuvchi u bilan chatni boshlagandan yoki bot guruhga qo‘shilgandan keyin o‘sha chatdan keladigan xabarlarni oladi.
|
|
139
|
+
- Python SDK tokeni faol bo‘lsa, shu bot uchun SaloScript avtomatik javob berishi to‘xtaydi. Tokenni bekor qilsangiz, SaloScript rejimi qayta ishlaydi.
|
|
140
|
+
- SDK serverida Python jarayonini o‘zingiz ishga tushirasiz. Salogram sizning Python kodingizni o‘z Flask jarayonida `exec()` qilmaydi.
|
|
141
|
+
- Tokenni hech qachon frontend JavaScript, ochiq repository yoki umumiy chatga joylamang. Token oshkor bo‘lsa, Bot Studio'da darhol yangilang yoki bekor qiling.
|
|
142
|
+
- API token faqat o‘z botingiz nomidan xabar yuborish va botga kelgan hodisalarni olish huquqini beradi. Foydalanuvchilarning parollari yoki sessiyalariga kirish huquqini bermaydi.
|
|
143
|
+
|
|
144
|
+
## API manzillari
|
|
145
|
+
|
|
146
|
+
SDK ichki ravishda quyidagi HTTPS endpointlardan foydalanadi:
|
|
147
|
+
|
|
148
|
+
- `GET /api/v1/bot/me`
|
|
149
|
+
- `GET /api/v1/bot/updates`
|
|
150
|
+
- `POST /api/v1/bot/sendMessage`
|
|
151
|
+
- `POST /api/v1/bot/upload`
|
|
152
|
+
- `GET|PUT|DELETE /api/v1/bot/storage/<key>`
|
|
153
|
+
|
|
154
|
+
Bularni qo‘lda chaqirish shart emas — `Bot` klassi hammasini boshqaradi.
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
# Salogram Bot SDK for Python
|
|
2
|
+
|
|
3
|
+
Salogram botlarini oddiy Python orqali yaratish uchun rasmiy kutubxona. Bot dasturi dasturchining o‘z kompyuteri yoki serverida ishlaydi va Salogram bilan HTTPS orqali muloqot qiladi. Kutubxona Python standart kutubxonasidan foydalanadi — `requests` yoki boshqa qo‘shimcha paket talab qilinmaydi.
|
|
4
|
+
|
|
5
|
+
## O‘rnatish
|
|
6
|
+
|
|
7
|
+
ZIP arxivni oching, terminalda `salogram-bot-sdk` papkasiga kiring va:
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
python -m pip install .
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Kutubxona hali PyPI'ga chiqarilmagan. Shu sababli `pip install salogram-bot` global PyPI buyrug‘i hozircha ishlamasligi mumkin; yuqoridagi lokal o‘rnatish usulidan foydalaning.
|
|
14
|
+
|
|
15
|
+
## Token olish
|
|
16
|
+
|
|
17
|
+
1. Salogram akkauntingizga kiring.
|
|
18
|
+
2. Bot Studio'ni oching va kerakli botni tanlang.
|
|
19
|
+
3. **Sozlamalar → Python SDK · API token → Token yaratish** ni bosing.
|
|
20
|
+
4. Tokenni nusxalab, o‘z dasturingizdagi xavfsiz muhit o‘zgaruvchisida saqlang.
|
|
21
|
+
5. Token sahifadan chiqilgach qayta ko‘rsatilmaydi. Yo‘qolsa, Bot Studio'dan yangisini yarating. Yangisini yaratish eskisini bekor qiladi.
|
|
22
|
+
|
|
23
|
+
## Birinchi bot
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
import os
|
|
27
|
+
from salobot import Bot
|
|
28
|
+
|
|
29
|
+
bot = Bot(
|
|
30
|
+
token=os.environ["SALOGRAM_BOT_TOKEN"],
|
|
31
|
+
base_url="https://salogram.pythonanywhere.com",
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
@bot.command("start")
|
|
35
|
+
async def start(ctx):
|
|
36
|
+
await ctx.reply(f"Salom, {ctx.user.name}! Men Python orqali ishlaydigan SaloBotman.")
|
|
37
|
+
|
|
38
|
+
@bot.command("help")
|
|
39
|
+
async def help_command(ctx):
|
|
40
|
+
await ctx.reply("Mavjud buyruqlar: /start, /help")
|
|
41
|
+
|
|
42
|
+
@bot.on_message()
|
|
43
|
+
async def echo(ctx):
|
|
44
|
+
if ctx.text and not ctx.text.startswith("/"):
|
|
45
|
+
await ctx.reply("Siz yozdingiz: " + ctx.text)
|
|
46
|
+
|
|
47
|
+
bot.run()
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Windows PowerShell'da tokenni vaqtincha belgilash:
|
|
51
|
+
|
|
52
|
+
```powershell
|
|
53
|
+
$env:SALOGRAM_BOT_TOKEN="sbot_your_token_here"
|
|
54
|
+
python bot.py
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Tugmalar va callback
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
from salobot import Bot, Button
|
|
61
|
+
|
|
62
|
+
bot = Bot(token="sbot_...", base_url="https://salogram.pythonanywhere.com")
|
|
63
|
+
|
|
64
|
+
@bot.command("start")
|
|
65
|
+
async def start(ctx):
|
|
66
|
+
await ctx.reply("Bo‘limni tanlang:", buttons=[
|
|
67
|
+
Button("Yangiliklar", "news"),
|
|
68
|
+
Button("Yordam", "help"),
|
|
69
|
+
])
|
|
70
|
+
|
|
71
|
+
@bot.on_callback()
|
|
72
|
+
async def on_button(ctx):
|
|
73
|
+
if ctx.callback == "news":
|
|
74
|
+
await ctx.reply("Salogram yangiliklari!")
|
|
75
|
+
elif ctx.callback == "help":
|
|
76
|
+
await ctx.reply("Yordam uchun /help buyrug‘ini yuboring.")
|
|
77
|
+
|
|
78
|
+
bot.run()
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Fayllar yuborish
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
@bot.command("photo")
|
|
85
|
+
async def photo(ctx):
|
|
86
|
+
await ctx.reply_photo("rasm.jpg", caption="Salomogramdan rasm")
|
|
87
|
+
|
|
88
|
+
@bot.command("file")
|
|
89
|
+
async def file(ctx):
|
|
90
|
+
await ctx.reply_file("document.pdf", caption="Hujjat")
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
`send_video()` va `send_audio()` metodlari ham mavjud. Fayllar botning Salogram storage kvotasiga saqlanadi.
|
|
94
|
+
|
|
95
|
+
## Doimiy xotira
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
@bot.command("remember")
|
|
99
|
+
async def remember(ctx):
|
|
100
|
+
await bot.set_user_data(ctx.user.id, "favorite_color", "green")
|
|
101
|
+
await ctx.reply("Saqladim!")
|
|
102
|
+
|
|
103
|
+
@bot.command("color")
|
|
104
|
+
async def color(ctx):
|
|
105
|
+
value = await bot.get_user_data(ctx.user.id, "favorite_color", "noma'lum")
|
|
106
|
+
await ctx.reply("Sevimli rang: " + str(value))
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Umumiy bot xotirasi uchun `set_data()`, `get_data()` va `delete_data()` ishlatiladi.
|
|
110
|
+
|
|
111
|
+
## Qo‘llab-quvvatlanadigan imkoniyatlar
|
|
112
|
+
|
|
113
|
+
- `@bot.command("name")` — buyruqlar.
|
|
114
|
+
- `@bot.on_message()` — oddiy xabarlar.
|
|
115
|
+
- `@bot.on_callback()` — inline tugma callback hodisalari.
|
|
116
|
+
- `ctx.reply()` — xabar yuborish.
|
|
117
|
+
- `ctx.reply_photo()`, `ctx.reply_file()` — media/fayl yuborish.
|
|
118
|
+
- `bot.send_video()`, `bot.send_audio()`, `bot.send_document()` — video, audio va hujjat.
|
|
119
|
+
- `bot.get_me()` — bot profilini olish.
|
|
120
|
+
- `bot.set_data()/get_data()/delete_data()` — umumiy saqlash.
|
|
121
|
+
- `bot.set_user_data()/get_user_data()/delete_user_data()` — foydalanuvchiga tegishli xotira.
|
|
122
|
+
- Botning chatdagi xabarlari va fayllari Salogram'da ko‘rinadi.
|
|
123
|
+
|
|
124
|
+
## Muhim qoidalar
|
|
125
|
+
|
|
126
|
+
- Bot foydalanuvchi u bilan chatni boshlagandan yoki bot guruhga qo‘shilgandan keyin o‘sha chatdan keladigan xabarlarni oladi.
|
|
127
|
+
- Python SDK tokeni faol bo‘lsa, shu bot uchun SaloScript avtomatik javob berishi to‘xtaydi. Tokenni bekor qilsangiz, SaloScript rejimi qayta ishlaydi.
|
|
128
|
+
- SDK serverida Python jarayonini o‘zingiz ishga tushirasiz. Salogram sizning Python kodingizni o‘z Flask jarayonida `exec()` qilmaydi.
|
|
129
|
+
- Tokenni hech qachon frontend JavaScript, ochiq repository yoki umumiy chatga joylamang. Token oshkor bo‘lsa, Bot Studio'da darhol yangilang yoki bekor qiling.
|
|
130
|
+
- API token faqat o‘z botingiz nomidan xabar yuborish va botga kelgan hodisalarni olish huquqini beradi. Foydalanuvchilarning parollari yoki sessiyalariga kirish huquqini bermaydi.
|
|
131
|
+
|
|
132
|
+
## API manzillari
|
|
133
|
+
|
|
134
|
+
SDK ichki ravishda quyidagi HTTPS endpointlardan foydalanadi:
|
|
135
|
+
|
|
136
|
+
- `GET /api/v1/bot/me`
|
|
137
|
+
- `GET /api/v1/bot/updates`
|
|
138
|
+
- `POST /api/v1/bot/sendMessage`
|
|
139
|
+
- `POST /api/v1/bot/upload`
|
|
140
|
+
- `GET|PUT|DELETE /api/v1/bot/storage/<key>`
|
|
141
|
+
|
|
142
|
+
Bularni qo‘lda chaqirish shart emas — `Bot` klassi hammasini boshqaradi.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "salogram-bot"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "Official Python SDK for building bots on Salogram"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
authors = [{ name = "Salogram Developers" }]
|
|
12
|
+
keywords = ["salogram", "bot", "sdk", "chatbot"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Programming Language :: Python :: 3",
|
|
15
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
16
|
+
"Operating System :: OS Independent",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
[tool.setuptools]
|
|
20
|
+
py-modules = ["salobot"]
|
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
"""Official Salogram Python Bot SDK.
|
|
2
|
+
|
|
3
|
+
This package uses only the Python standard library. Bot code runs on the
|
|
4
|
+
programmer's own computer/server and connects to Salogram over HTTPS.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
import hashlib
|
|
10
|
+
import http.client
|
|
11
|
+
import inspect
|
|
12
|
+
import json
|
|
13
|
+
import logging
|
|
14
|
+
import mimetypes
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
import time
|
|
18
|
+
import urllib.error
|
|
19
|
+
import urllib.parse
|
|
20
|
+
import urllib.request
|
|
21
|
+
import uuid
|
|
22
|
+
from dataclasses import dataclass
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from types import SimpleNamespace
|
|
25
|
+
from typing import Any, Callable, Dict, Iterable, List, Optional
|
|
26
|
+
|
|
27
|
+
__version__ = "1.0.0"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class SaloBotError(Exception):
|
|
31
|
+
"""Base SDK exception."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class SaloBotAPIError(SaloBotError):
|
|
35
|
+
"""An HTTP/API error returned by Salogram."""
|
|
36
|
+
|
|
37
|
+
def __init__(self, message: str, status: int = 0, code: str = ""):
|
|
38
|
+
super().__init__(message)
|
|
39
|
+
self.status = status
|
|
40
|
+
self.code = code
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class Button:
|
|
45
|
+
"""A callback button displayed below a bot message."""
|
|
46
|
+
|
|
47
|
+
text: str
|
|
48
|
+
callback: str
|
|
49
|
+
|
|
50
|
+
def to_dict(self) -> Dict[str, str]:
|
|
51
|
+
return {"text": str(self.text), "callback": str(self.callback)}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _plain(value: Any) -> Any:
|
|
55
|
+
if isinstance(value, Button):
|
|
56
|
+
return value.to_dict()
|
|
57
|
+
if isinstance(value, (list, tuple)):
|
|
58
|
+
return [_plain(item) for item in value]
|
|
59
|
+
if isinstance(value, dict):
|
|
60
|
+
return {str(key): _plain(item) for key, item in value.items()}
|
|
61
|
+
return value
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _namespace(value: Any) -> Any:
|
|
65
|
+
if isinstance(value, dict):
|
|
66
|
+
return SimpleNamespace(**{key: _namespace(item) for key, item in value.items()})
|
|
67
|
+
if isinstance(value, list):
|
|
68
|
+
return [_namespace(item) for item in value]
|
|
69
|
+
return value
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class _HTTPClient:
|
|
73
|
+
def __init__(self, token: str, base_url: str, timeout: float = 30.0):
|
|
74
|
+
token = str(token or "").strip()
|
|
75
|
+
if not token.startswith("sbot_") or len(token) < 30:
|
|
76
|
+
raise ValueError("Salogram bot token noto‘g‘ri ko‘rinadi.")
|
|
77
|
+
base_url = str(base_url or "").strip().rstrip("/")
|
|
78
|
+
if not base_url.startswith(("https://", "http://")):
|
|
79
|
+
raise ValueError("base_url https:// yoki http:// bilan boshlanishi kerak.")
|
|
80
|
+
self.token = token
|
|
81
|
+
self.base_url = base_url
|
|
82
|
+
self.timeout = max(3.0, float(timeout))
|
|
83
|
+
|
|
84
|
+
def request(self, method: str, endpoint: str, *, params: Optional[dict] = None,
|
|
85
|
+
payload: Optional[dict] = None, body: Optional[bytes] = None,
|
|
86
|
+
content_type: Optional[str] = None) -> dict:
|
|
87
|
+
url = self.base_url + endpoint
|
|
88
|
+
if params:
|
|
89
|
+
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
|
|
90
|
+
headers = {"Authorization": "Bearer " + self.token, "Accept": "application/json"}
|
|
91
|
+
if payload is not None:
|
|
92
|
+
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
|
93
|
+
headers["Content-Type"] = "application/json; charset=utf-8"
|
|
94
|
+
elif content_type:
|
|
95
|
+
headers["Content-Type"] = content_type
|
|
96
|
+
req = urllib.request.Request(url, data=body, headers=headers, method=method.upper())
|
|
97
|
+
try:
|
|
98
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as response:
|
|
99
|
+
raw = response.read()
|
|
100
|
+
result = json.loads(raw.decode("utf-8")) if raw else {}
|
|
101
|
+
if not isinstance(result, dict):
|
|
102
|
+
raise SaloBotAPIError("Salogram serveridan noto‘g‘ri javob olindi.")
|
|
103
|
+
return result
|
|
104
|
+
except urllib.error.HTTPError as exc:
|
|
105
|
+
try:
|
|
106
|
+
details = json.loads(exc.read().decode("utf-8"))
|
|
107
|
+
except Exception:
|
|
108
|
+
details = {}
|
|
109
|
+
raise SaloBotAPIError(
|
|
110
|
+
str(details.get("error") or "Salogram API so‘rovni rad etdi."),
|
|
111
|
+
status=int(exc.code), code=str(details.get("code") or "")
|
|
112
|
+
) from exc
|
|
113
|
+
except urllib.error.URLError as exc:
|
|
114
|
+
raise SaloBotAPIError("Salogram serveriga ulanib bo‘lmadi: " + str(exc.reason)) from exc
|
|
115
|
+
except (TimeoutError, OSError) as exc:
|
|
116
|
+
raise SaloBotAPIError("Tarmoq xatosi: " + str(exc)) from exc
|
|
117
|
+
except json.JSONDecodeError as exc:
|
|
118
|
+
raise SaloBotAPIError("Salogram serveridan JSON javob olinmadi.") from exc
|
|
119
|
+
|
|
120
|
+
def upload(self, path: str) -> dict:
|
|
121
|
+
file_path = Path(path).expanduser()
|
|
122
|
+
if not file_path.is_file():
|
|
123
|
+
raise FileNotFoundError(str(file_path))
|
|
124
|
+
size = file_path.stat().st_size
|
|
125
|
+
if size <= 0:
|
|
126
|
+
raise ValueError("Bo‘sh fayl yuborib bo‘lmaydi.")
|
|
127
|
+
if size > 200 * 1024 * 1024:
|
|
128
|
+
raise ValueError("Fayl 200 MB dan kichik bo‘lishi kerak.")
|
|
129
|
+
name = file_path.name.replace('"', "_").replace("\r", "_").replace("\n", "_")
|
|
130
|
+
mime = mimetypes.guess_type(name)[0] or "application/octet-stream"
|
|
131
|
+
boundary = "----SaloBot" + uuid.uuid4().hex
|
|
132
|
+
prefix = (
|
|
133
|
+
("--" + boundary + "\r\n").encode()
|
|
134
|
+
+ (f'Content-Disposition: form-data; name="file"; filename="{name}"\r\n').encode("utf-8")
|
|
135
|
+
+ (f"Content-Type: {mime}\r\n\r\n").encode("ascii")
|
|
136
|
+
)
|
|
137
|
+
suffix = ("\r\n--" + boundary + "--\r\n").encode()
|
|
138
|
+
parsed = urllib.parse.urlsplit(self.base_url)
|
|
139
|
+
connection_type = http.client.HTTPSConnection if parsed.scheme == "https" else http.client.HTTPConnection
|
|
140
|
+
connection = connection_type(parsed.hostname, parsed.port, timeout=self.timeout)
|
|
141
|
+
target = (parsed.path.rstrip("/") + "/api/v1/bot/upload") or "/api/v1/bot/upload"
|
|
142
|
+
try:
|
|
143
|
+
connection.putrequest("POST", target)
|
|
144
|
+
connection.putheader("Authorization", "Bearer " + self.token)
|
|
145
|
+
connection.putheader("Accept", "application/json")
|
|
146
|
+
connection.putheader("Content-Type", "multipart/form-data; boundary=" + boundary)
|
|
147
|
+
connection.putheader("Content-Length", str(len(prefix) + size + len(suffix)))
|
|
148
|
+
connection.endheaders()
|
|
149
|
+
connection.send(prefix)
|
|
150
|
+
with file_path.open("rb") as stream:
|
|
151
|
+
while True:
|
|
152
|
+
chunk = stream.read(1024 * 1024)
|
|
153
|
+
if not chunk:
|
|
154
|
+
break
|
|
155
|
+
connection.send(chunk)
|
|
156
|
+
connection.send(suffix)
|
|
157
|
+
response = connection.getresponse()
|
|
158
|
+
raw = response.read()
|
|
159
|
+
try:
|
|
160
|
+
result = json.loads(raw.decode("utf-8")) if raw else {}
|
|
161
|
+
except json.JSONDecodeError as exc:
|
|
162
|
+
raise SaloBotAPIError("Salogram serveridan JSON javob olinmadi.", status=response.status) from exc
|
|
163
|
+
if response.status >= 400:
|
|
164
|
+
raise SaloBotAPIError(str(result.get("error") or "Fayl yuklash amalga oshmadi."),
|
|
165
|
+
status=response.status, code=str(result.get("code") or ""))
|
|
166
|
+
if not isinstance(result, dict):
|
|
167
|
+
raise SaloBotAPIError("Salogram serveridan noto‘g‘ri javob olindi.")
|
|
168
|
+
return result
|
|
169
|
+
except OSError as exc:
|
|
170
|
+
raise SaloBotAPIError("Fayl yuklashda tarmoq xatosi: " + str(exc)) from exc
|
|
171
|
+
finally:
|
|
172
|
+
connection.close()
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class Context:
|
|
176
|
+
"""A single incoming message or callback passed to a handler."""
|
|
177
|
+
|
|
178
|
+
def __init__(self, bot: "Bot", update: dict):
|
|
179
|
+
self.bot = bot
|
|
180
|
+
self.update = update
|
|
181
|
+
self.type = str(update.get("type") or "")
|
|
182
|
+
self.raw = update
|
|
183
|
+
if self.type == "callback":
|
|
184
|
+
raw = update.get("callback_query") or {}
|
|
185
|
+
self.callback = str(raw.get("data") or "")
|
|
186
|
+
self.callback_id = str(raw.get("id") or "")
|
|
187
|
+
self.message = _namespace(raw.get("message") or {})
|
|
188
|
+
self.user = _namespace(raw.get("from") or {})
|
|
189
|
+
self.chat = _namespace(raw.get("chat") or {})
|
|
190
|
+
self.text = self.callback
|
|
191
|
+
self.args: List[str] = []
|
|
192
|
+
else:
|
|
193
|
+
raw = update.get("message") or {}
|
|
194
|
+
self.callback = ""
|
|
195
|
+
self.callback_id = ""
|
|
196
|
+
self.message = _namespace(raw)
|
|
197
|
+
self.user = _namespace(raw.get("from") or {})
|
|
198
|
+
self.chat = _namespace(raw.get("chat") or {})
|
|
199
|
+
self.caption = str(raw.get("caption") or "")
|
|
200
|
+
self.text = str(raw.get("text") or self.caption or (raw.get("content") if raw.get("type") == "text" else "") or "")
|
|
201
|
+
self.args = self._command_args(self.text)
|
|
202
|
+
self.from_user = self.user
|
|
203
|
+
self.chat_id = str(getattr(self.chat, "id", "") or "")
|
|
204
|
+
|
|
205
|
+
@staticmethod
|
|
206
|
+
def _command_args(text: str) -> List[str]:
|
|
207
|
+
parts = str(text or "").strip().split()
|
|
208
|
+
return parts[1:] if parts and parts[0].startswith("/") else []
|
|
209
|
+
|
|
210
|
+
async def reply(self, text: str, *, buttons: Optional[Iterable[Any]] = None,
|
|
211
|
+
reply_to: Optional[str] = None) -> dict:
|
|
212
|
+
return await self.bot.send_message(self.chat_id, text, buttons=buttons,
|
|
213
|
+
reply_to=reply_to or getattr(self.message, "id", None))
|
|
214
|
+
|
|
215
|
+
async def reply_photo(self, path: str, caption: str = "", *, buttons=None) -> dict:
|
|
216
|
+
return await self.bot.send_photo(self.chat_id, path, caption=caption, buttons=buttons)
|
|
217
|
+
|
|
218
|
+
async def reply_file(self, path: str, caption: str = "", *, buttons=None) -> dict:
|
|
219
|
+
return await self.bot.send_file(self.chat_id, path, caption=caption, buttons=buttons)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
class Bot:
|
|
223
|
+
"""Create a Python-powered Salogram bot.
|
|
224
|
+
|
|
225
|
+
Example:
|
|
226
|
+
bot = Bot(token="sbot_...", base_url="https://salogram.example")
|
|
227
|
+
|
|
228
|
+
@bot.command("start")
|
|
229
|
+
async def start(ctx):
|
|
230
|
+
await ctx.reply("Salom!")
|
|
231
|
+
|
|
232
|
+
bot.run()
|
|
233
|
+
"""
|
|
234
|
+
|
|
235
|
+
def __init__(self, token: str, base_url: str, *, request_timeout: float = 30.0,
|
|
236
|
+
poll_timeout: int = 0, offset_file: Optional[str] = None,
|
|
237
|
+
logger: Optional[logging.Logger] = None):
|
|
238
|
+
self._http = _HTTPClient(token, base_url, request_timeout)
|
|
239
|
+
self.poll_timeout = max(0, min(20, int(poll_timeout)))
|
|
240
|
+
self.logger = logger or logging.getLogger("salobot")
|
|
241
|
+
self._message_handlers: List[Callable] = []
|
|
242
|
+
self._callback_handlers: List[Callable] = []
|
|
243
|
+
self._command_handlers: Dict[str, Callable] = {}
|
|
244
|
+
self._event_handlers: Dict[str, List[Callable]] = {}
|
|
245
|
+
self._startup_handlers: List[Callable] = []
|
|
246
|
+
self._stopping = False
|
|
247
|
+
self.me: Optional[dict] = None
|
|
248
|
+
digest = hashlib.sha256(self._http.token.encode("utf-8")).hexdigest()[:16]
|
|
249
|
+
default_offset = Path.home() / ".salobot" / ("offset_" + digest + ".json")
|
|
250
|
+
self.offset_path = Path(offset_file).expanduser() if offset_file else default_offset
|
|
251
|
+
self.offset = self._load_offset()
|
|
252
|
+
|
|
253
|
+
def on_message(self, handler: Optional[Callable] = None):
|
|
254
|
+
def decorator(fn):
|
|
255
|
+
self._message_handlers.append(fn)
|
|
256
|
+
return fn
|
|
257
|
+
return decorator(handler) if handler else decorator
|
|
258
|
+
|
|
259
|
+
def command(self, name: str):
|
|
260
|
+
command_name = str(name or "").strip().lstrip("/").lower()
|
|
261
|
+
if not re.fullmatch(r"[a-z0-9_]{1,32}", command_name):
|
|
262
|
+
raise ValueError("Command faqat lotin harflari, raqam va _ dan iborat bo‘lsin.")
|
|
263
|
+
def decorator(fn):
|
|
264
|
+
self._command_handlers[command_name] = fn
|
|
265
|
+
return fn
|
|
266
|
+
return decorator
|
|
267
|
+
|
|
268
|
+
def on_callback(self, handler: Optional[Callable] = None):
|
|
269
|
+
def decorator(fn):
|
|
270
|
+
self._callback_handlers.append(fn)
|
|
271
|
+
return fn
|
|
272
|
+
return decorator(handler) if handler else decorator
|
|
273
|
+
|
|
274
|
+
def on(self, event_name: str):
|
|
275
|
+
name = str(event_name or "").strip().lower()
|
|
276
|
+
if name not in ("message", "callback"):
|
|
277
|
+
raise ValueError("1.0 versiyada message va callback hodisalari qo‘llab-quvvatlanadi.")
|
|
278
|
+
def decorator(fn):
|
|
279
|
+
self._event_handlers.setdefault(name, []).append(fn)
|
|
280
|
+
return fn
|
|
281
|
+
return decorator
|
|
282
|
+
|
|
283
|
+
def on_startup(self, handler: Optional[Callable] = None):
|
|
284
|
+
def decorator(fn):
|
|
285
|
+
self._startup_handlers.append(fn)
|
|
286
|
+
return fn
|
|
287
|
+
return decorator(handler) if handler else decorator
|
|
288
|
+
|
|
289
|
+
async def _call(self, handler: Callable, ctx: Context):
|
|
290
|
+
result = handler(ctx)
|
|
291
|
+
if inspect.isawaitable(result):
|
|
292
|
+
await result
|
|
293
|
+
|
|
294
|
+
async def _api(self, method: str, endpoint: str, **kwargs) -> dict:
|
|
295
|
+
return await asyncio.to_thread(self._http.request, method, endpoint, **kwargs)
|
|
296
|
+
|
|
297
|
+
async def get_me(self) -> dict:
|
|
298
|
+
result = await self._api("GET", "/api/v1/bot/me")
|
|
299
|
+
self.me = result
|
|
300
|
+
return result
|
|
301
|
+
|
|
302
|
+
async def send_message(self, chat_id: str, text: str, *, buttons=None,
|
|
303
|
+
reply_to: Optional[str] = None) -> dict:
|
|
304
|
+
payload = {"chat_id": str(chat_id), "text": str(text), "buttons": _plain(buttons) if buttons is not None else None}
|
|
305
|
+
if reply_to:
|
|
306
|
+
payload["reply_to"] = str(reply_to)
|
|
307
|
+
return await self._api("POST", "/api/v1/bot/sendMessage", payload=payload)
|
|
308
|
+
|
|
309
|
+
async def send_file(self, chat_id: str, path: str, *, caption: str = "",
|
|
310
|
+
media_type: str = "file", buttons=None) -> dict:
|
|
311
|
+
uploaded = await asyncio.to_thread(self._http.upload, path)
|
|
312
|
+
file_info = uploaded.get("file") or {}
|
|
313
|
+
if not file_info.get("id"):
|
|
314
|
+
raise SaloBotAPIError("Fayl yuklandi, lekin file_id olinmadi.")
|
|
315
|
+
payload = {"chat_id": str(chat_id), "file_id": file_info["id"],
|
|
316
|
+
"type": str(media_type), "caption": str(caption),
|
|
317
|
+
"buttons": _plain(buttons) if buttons is not None else None}
|
|
318
|
+
return await self._api("POST", "/api/v1/bot/sendMessage", payload=payload)
|
|
319
|
+
|
|
320
|
+
async def send_photo(self, chat_id: str, path: str, *, caption: str = "", buttons=None) -> dict:
|
|
321
|
+
return await self.send_file(chat_id, path, caption=caption, media_type="image", buttons=buttons)
|
|
322
|
+
|
|
323
|
+
async def send_video(self, chat_id: str, path: str, *, caption: str = "", buttons=None) -> dict:
|
|
324
|
+
return await self.send_file(chat_id, path, caption=caption, media_type="video", buttons=buttons)
|
|
325
|
+
|
|
326
|
+
async def send_audio(self, chat_id: str, path: str, *, caption: str = "", buttons=None) -> dict:
|
|
327
|
+
return await self.send_file(chat_id, path, caption=caption, media_type="audio", buttons=buttons)
|
|
328
|
+
|
|
329
|
+
async def send_document(self, chat_id: str, path: str, *, caption: str = "", buttons=None) -> dict:
|
|
330
|
+
return await self.send_file(chat_id, path, caption=caption, media_type="document", buttons=buttons)
|
|
331
|
+
|
|
332
|
+
async def set_data(self, key: str, value: Any) -> dict:
|
|
333
|
+
return await self._api("PUT", "/api/v1/bot/storage/" + urllib.parse.quote(str(key), safe=""),
|
|
334
|
+
payload={"value": value})
|
|
335
|
+
|
|
336
|
+
async def get_data(self, key: str, default: Any = None) -> Any:
|
|
337
|
+
result = await self._api("GET", "/api/v1/bot/storage/" + urllib.parse.quote(str(key), safe=""))
|
|
338
|
+
return result.get("value", default) if result.get("found") else default
|
|
339
|
+
|
|
340
|
+
async def delete_data(self, key: str) -> bool:
|
|
341
|
+
result = await self._api("DELETE", "/api/v1/bot/storage/" + urllib.parse.quote(str(key), safe=""))
|
|
342
|
+
return bool(result.get("deleted"))
|
|
343
|
+
|
|
344
|
+
async def set_user_data(self, user_id: str, key: str, value: Any) -> dict:
|
|
345
|
+
params = urllib.parse.urlencode({"scope": "user", "user_id": str(user_id)})
|
|
346
|
+
return await self._api("PUT", "/api/v1/bot/storage/" + urllib.parse.quote(str(key), safe="") + "?" + params,
|
|
347
|
+
payload={"value": value})
|
|
348
|
+
|
|
349
|
+
async def get_user_data(self, user_id: str, key: str, default: Any = None) -> Any:
|
|
350
|
+
params = urllib.parse.urlencode({"scope": "user", "user_id": str(user_id)})
|
|
351
|
+
result = await self._api("GET", "/api/v1/bot/storage/" + urllib.parse.quote(str(key), safe="") + "?" + params)
|
|
352
|
+
return result.get("value", default) if result.get("found") else default
|
|
353
|
+
|
|
354
|
+
async def delete_user_data(self, user_id: str, key: str) -> bool:
|
|
355
|
+
params = urllib.parse.urlencode({"scope": "user", "user_id": str(user_id)})
|
|
356
|
+
result = await self._api("DELETE", "/api/v1/bot/storage/" + urllib.parse.quote(str(key), safe="") + "?" + params)
|
|
357
|
+
return bool(result.get("deleted"))
|
|
358
|
+
|
|
359
|
+
def _load_offset(self) -> int:
|
|
360
|
+
try:
|
|
361
|
+
data = json.loads(self.offset_path.read_text(encoding="utf-8"))
|
|
362
|
+
return max(0, int(data.get("offset", 0)))
|
|
363
|
+
except (OSError, ValueError, TypeError, json.JSONDecodeError):
|
|
364
|
+
return 0
|
|
365
|
+
|
|
366
|
+
def _save_offset(self):
|
|
367
|
+
try:
|
|
368
|
+
self.offset_path.parent.mkdir(parents=True, exist_ok=True)
|
|
369
|
+
temp = self.offset_path.with_suffix(self.offset_path.suffix + ".tmp")
|
|
370
|
+
temp.write_text(json.dumps({"offset": self.offset}), encoding="utf-8")
|
|
371
|
+
os.replace(str(temp), str(self.offset_path))
|
|
372
|
+
except OSError as exc:
|
|
373
|
+
self.logger.warning("Update cursor saqlanmadi: %s", exc)
|
|
374
|
+
|
|
375
|
+
async def _dispatch(self, update: dict):
|
|
376
|
+
event_type = str(update.get("type") or "")
|
|
377
|
+
ctx = Context(self, update)
|
|
378
|
+
handlers: List[Callable] = []
|
|
379
|
+
if event_type == "message":
|
|
380
|
+
handlers.extend(self._event_handlers.get("message", []))
|
|
381
|
+
handlers.extend(self._message_handlers)
|
|
382
|
+
first = (ctx.text.strip().split() or [""])[0]
|
|
383
|
+
if first.startswith("/"):
|
|
384
|
+
command = first[1:].split("@", 1)[0].lower()
|
|
385
|
+
command_handler = self._command_handlers.get(command)
|
|
386
|
+
if command_handler:
|
|
387
|
+
handlers.append(command_handler)
|
|
388
|
+
elif event_type == "callback":
|
|
389
|
+
handlers.extend(self._event_handlers.get("callback", []))
|
|
390
|
+
handlers.extend(self._callback_handlers)
|
|
391
|
+
for handler in handlers:
|
|
392
|
+
await self._call(handler, ctx)
|
|
393
|
+
|
|
394
|
+
async def start(self):
|
|
395
|
+
self._stopping = False
|
|
396
|
+
self.me = await self.get_me()
|
|
397
|
+
self.logger.info("@%s SaloBot SDK orqali ulandi", self.me.get("username", "bot"))
|
|
398
|
+
for handler in self._startup_handlers:
|
|
399
|
+
result = handler(self)
|
|
400
|
+
if inspect.isawaitable(result):
|
|
401
|
+
await result
|
|
402
|
+
delay = 1.0
|
|
403
|
+
while not self._stopping:
|
|
404
|
+
try:
|
|
405
|
+
result = await self._api("GET", "/api/v1/bot/updates", params={
|
|
406
|
+
"offset": self.offset, "limit": 100, "timeout": self.poll_timeout
|
|
407
|
+
})
|
|
408
|
+
updates = result.get("updates") or []
|
|
409
|
+
for update in updates:
|
|
410
|
+
try:
|
|
411
|
+
await self._dispatch(update)
|
|
412
|
+
except Exception:
|
|
413
|
+
self.logger.exception("Update %s handlerida xatolik", update.get("update_id"))
|
|
414
|
+
self.offset = max(self.offset, int(update.get("update_id", 0) or 0))
|
|
415
|
+
self._save_offset()
|
|
416
|
+
if not updates:
|
|
417
|
+
# Short polling avoids holding a Salogram web worker open for long periods.
|
|
418
|
+
await asyncio.sleep(1.0)
|
|
419
|
+
delay = 1.0
|
|
420
|
+
except SaloBotAPIError as exc:
|
|
421
|
+
self.logger.warning("Salogram API: %s", exc)
|
|
422
|
+
if exc.status in (401, 403):
|
|
423
|
+
self.logger.error("Token bekor qilingan yoki ruxsat yo‘q. Bot to‘xtatildi.")
|
|
424
|
+
return
|
|
425
|
+
await asyncio.sleep(delay)
|
|
426
|
+
delay = min(delay * 2, 30.0)
|
|
427
|
+
except Exception:
|
|
428
|
+
self.logger.exception("Bot polling jarayonida xatolik")
|
|
429
|
+
await asyncio.sleep(delay)
|
|
430
|
+
delay = min(delay * 2, 30.0)
|
|
431
|
+
|
|
432
|
+
def stop(self):
|
|
433
|
+
self._stopping = True
|
|
434
|
+
|
|
435
|
+
def run(self):
|
|
436
|
+
"""Start the bot polling loop. Press Ctrl+C to stop it."""
|
|
437
|
+
try:
|
|
438
|
+
asyncio.run(self.start())
|
|
439
|
+
except KeyboardInterrupt:
|
|
440
|
+
self.stop()
|
|
441
|
+
self.logger.info("SaloBot to‘xtatildi")
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
__all__ = ["Bot", "Button", "Context", "SaloBotError", "SaloBotAPIError", "__version__"]
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: salogram-bot
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Official Python SDK for building bots on Salogram
|
|
5
|
+
Author: Salogram Developers
|
|
6
|
+
Keywords: salogram,bot,sdk,chatbot
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Requires-Python: >=3.9
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# Salogram Bot SDK for Python
|
|
14
|
+
|
|
15
|
+
Salogram botlarini oddiy Python orqali yaratish uchun rasmiy kutubxona. Bot dasturi dasturchining o‘z kompyuteri yoki serverida ishlaydi va Salogram bilan HTTPS orqali muloqot qiladi. Kutubxona Python standart kutubxonasidan foydalanadi — `requests` yoki boshqa qo‘shimcha paket talab qilinmaydi.
|
|
16
|
+
|
|
17
|
+
## O‘rnatish
|
|
18
|
+
|
|
19
|
+
ZIP arxivni oching, terminalda `salogram-bot-sdk` papkasiga kiring va:
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
python -m pip install .
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Kutubxona hali PyPI'ga chiqarilmagan. Shu sababli `pip install salogram-bot` global PyPI buyrug‘i hozircha ishlamasligi mumkin; yuqoridagi lokal o‘rnatish usulidan foydalaning.
|
|
26
|
+
|
|
27
|
+
## Token olish
|
|
28
|
+
|
|
29
|
+
1. Salogram akkauntingizga kiring.
|
|
30
|
+
2. Bot Studio'ni oching va kerakli botni tanlang.
|
|
31
|
+
3. **Sozlamalar → Python SDK · API token → Token yaratish** ni bosing.
|
|
32
|
+
4. Tokenni nusxalab, o‘z dasturingizdagi xavfsiz muhit o‘zgaruvchisida saqlang.
|
|
33
|
+
5. Token sahifadan chiqilgach qayta ko‘rsatilmaydi. Yo‘qolsa, Bot Studio'dan yangisini yarating. Yangisini yaratish eskisini bekor qiladi.
|
|
34
|
+
|
|
35
|
+
## Birinchi bot
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
import os
|
|
39
|
+
from salobot import Bot
|
|
40
|
+
|
|
41
|
+
bot = Bot(
|
|
42
|
+
token=os.environ["SALOGRAM_BOT_TOKEN"],
|
|
43
|
+
base_url="https://salogram.pythonanywhere.com",
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
@bot.command("start")
|
|
47
|
+
async def start(ctx):
|
|
48
|
+
await ctx.reply(f"Salom, {ctx.user.name}! Men Python orqali ishlaydigan SaloBotman.")
|
|
49
|
+
|
|
50
|
+
@bot.command("help")
|
|
51
|
+
async def help_command(ctx):
|
|
52
|
+
await ctx.reply("Mavjud buyruqlar: /start, /help")
|
|
53
|
+
|
|
54
|
+
@bot.on_message()
|
|
55
|
+
async def echo(ctx):
|
|
56
|
+
if ctx.text and not ctx.text.startswith("/"):
|
|
57
|
+
await ctx.reply("Siz yozdingiz: " + ctx.text)
|
|
58
|
+
|
|
59
|
+
bot.run()
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Windows PowerShell'da tokenni vaqtincha belgilash:
|
|
63
|
+
|
|
64
|
+
```powershell
|
|
65
|
+
$env:SALOGRAM_BOT_TOKEN="sbot_your_token_here"
|
|
66
|
+
python bot.py
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Tugmalar va callback
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
from salobot import Bot, Button
|
|
73
|
+
|
|
74
|
+
bot = Bot(token="sbot_...", base_url="https://salogram.pythonanywhere.com")
|
|
75
|
+
|
|
76
|
+
@bot.command("start")
|
|
77
|
+
async def start(ctx):
|
|
78
|
+
await ctx.reply("Bo‘limni tanlang:", buttons=[
|
|
79
|
+
Button("Yangiliklar", "news"),
|
|
80
|
+
Button("Yordam", "help"),
|
|
81
|
+
])
|
|
82
|
+
|
|
83
|
+
@bot.on_callback()
|
|
84
|
+
async def on_button(ctx):
|
|
85
|
+
if ctx.callback == "news":
|
|
86
|
+
await ctx.reply("Salogram yangiliklari!")
|
|
87
|
+
elif ctx.callback == "help":
|
|
88
|
+
await ctx.reply("Yordam uchun /help buyrug‘ini yuboring.")
|
|
89
|
+
|
|
90
|
+
bot.run()
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## Fayllar yuborish
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
@bot.command("photo")
|
|
97
|
+
async def photo(ctx):
|
|
98
|
+
await ctx.reply_photo("rasm.jpg", caption="Salomogramdan rasm")
|
|
99
|
+
|
|
100
|
+
@bot.command("file")
|
|
101
|
+
async def file(ctx):
|
|
102
|
+
await ctx.reply_file("document.pdf", caption="Hujjat")
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
`send_video()` va `send_audio()` metodlari ham mavjud. Fayllar botning Salogram storage kvotasiga saqlanadi.
|
|
106
|
+
|
|
107
|
+
## Doimiy xotira
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
@bot.command("remember")
|
|
111
|
+
async def remember(ctx):
|
|
112
|
+
await bot.set_user_data(ctx.user.id, "favorite_color", "green")
|
|
113
|
+
await ctx.reply("Saqladim!")
|
|
114
|
+
|
|
115
|
+
@bot.command("color")
|
|
116
|
+
async def color(ctx):
|
|
117
|
+
value = await bot.get_user_data(ctx.user.id, "favorite_color", "noma'lum")
|
|
118
|
+
await ctx.reply("Sevimli rang: " + str(value))
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Umumiy bot xotirasi uchun `set_data()`, `get_data()` va `delete_data()` ishlatiladi.
|
|
122
|
+
|
|
123
|
+
## Qo‘llab-quvvatlanadigan imkoniyatlar
|
|
124
|
+
|
|
125
|
+
- `@bot.command("name")` — buyruqlar.
|
|
126
|
+
- `@bot.on_message()` — oddiy xabarlar.
|
|
127
|
+
- `@bot.on_callback()` — inline tugma callback hodisalari.
|
|
128
|
+
- `ctx.reply()` — xabar yuborish.
|
|
129
|
+
- `ctx.reply_photo()`, `ctx.reply_file()` — media/fayl yuborish.
|
|
130
|
+
- `bot.send_video()`, `bot.send_audio()`, `bot.send_document()` — video, audio va hujjat.
|
|
131
|
+
- `bot.get_me()` — bot profilini olish.
|
|
132
|
+
- `bot.set_data()/get_data()/delete_data()` — umumiy saqlash.
|
|
133
|
+
- `bot.set_user_data()/get_user_data()/delete_user_data()` — foydalanuvchiga tegishli xotira.
|
|
134
|
+
- Botning chatdagi xabarlari va fayllari Salogram'da ko‘rinadi.
|
|
135
|
+
|
|
136
|
+
## Muhim qoidalar
|
|
137
|
+
|
|
138
|
+
- Bot foydalanuvchi u bilan chatni boshlagandan yoki bot guruhga qo‘shilgandan keyin o‘sha chatdan keladigan xabarlarni oladi.
|
|
139
|
+
- Python SDK tokeni faol bo‘lsa, shu bot uchun SaloScript avtomatik javob berishi to‘xtaydi. Tokenni bekor qilsangiz, SaloScript rejimi qayta ishlaydi.
|
|
140
|
+
- SDK serverida Python jarayonini o‘zingiz ishga tushirasiz. Salogram sizning Python kodingizni o‘z Flask jarayonida `exec()` qilmaydi.
|
|
141
|
+
- Tokenni hech qachon frontend JavaScript, ochiq repository yoki umumiy chatga joylamang. Token oshkor bo‘lsa, Bot Studio'da darhol yangilang yoki bekor qiling.
|
|
142
|
+
- API token faqat o‘z botingiz nomidan xabar yuborish va botga kelgan hodisalarni olish huquqini beradi. Foydalanuvchilarning parollari yoki sessiyalariga kirish huquqini bermaydi.
|
|
143
|
+
|
|
144
|
+
## API manzillari
|
|
145
|
+
|
|
146
|
+
SDK ichki ravishda quyidagi HTTPS endpointlardan foydalanadi:
|
|
147
|
+
|
|
148
|
+
- `GET /api/v1/bot/me`
|
|
149
|
+
- `GET /api/v1/bot/updates`
|
|
150
|
+
- `POST /api/v1/bot/sendMessage`
|
|
151
|
+
- `POST /api/v1/bot/upload`
|
|
152
|
+
- `GET|PUT|DELETE /api/v1/bot/storage/<key>`
|
|
153
|
+
|
|
154
|
+
Bularni qo‘lda chaqirish shart emas — `Bot` klassi hammasini boshqaradi.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
salobot
|