Репозиторий со сниппетами для быстрого старта Telegram-ботов с использованием pyTelegramBotAPI и баз данных (JSON, SQLite).
database/json_setup.py
import json
def init_json_db():
try:
with open('bot_data.json', 'r', encoding='utf-8') as file:
data = json.load(file)
except FileNotFoundError:
data = {'users': [], 'cars': []}
with open('bot_data.json', 'w', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=4)
return datadatabase/sqlite_setup.py
import sqlite3
import json
def init_sqlite_db():
conn = sqlite3.connect('bot.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY, telegram_id TEXT, username TEXT)''')
conn.commit()
conn.close()
def sqlite_to_json():
conn = sqlite3.connect('bot.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
data = [{'id': row[0], 'telegram_id': row[1], 'username': row[2]} for row in rows]
with open('bot_data.json', 'w', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=4)
conn.close()bot/basic_bot.py
import telebot
API_TOKEN = 'YOUR_BOT_TOKEN'
bot = telebot.TeleBot(API_TOKEN)
@bot.message_handler(commands=['start'])
def send_welcome(message):
bot.reply_to(message, "Привет! Я твой бот.")
@bot.message_handler(content_types=['text'])
def echo(message):
bot.reply_to(message, message.text)
bot.polling()bot/inline_bot.py
import telebot
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
API_TOKEN = 'YOUR_BOT_TOKEN'
bot = telebot.TeleBot(API_TOKEN)
def gen_inline_keyboard():
keyboard = InlineKeyboardMarkup()
button = InlineKeyboardButton(text="Нажми меня!", callback_data="button1")
keyboard.add(button)
return keyboard
@bot.message_handler(commands=['start'])
def send_welcome(message):
bot.reply_to(message, "Добро пожаловать!", reply_markup=gen_inline_keyboard())
@bot.callback_query_handler(func=lambda call: True)
def callback_inline(call):
if call.data == "button1":
bot.answer_callback_query(call.id, "Кнопка нажата!")
bot.polling()bot/car_example.py
import json
import telebot
API_TOKEN = 'YOUR_BOT_TOKEN'
class Car:
def __init__(self, id, model, year, color):
self.id = id
self.model = model
self.year = year
self.color = color
def __str__(self):
return f"{self.model} ({self.year}), цвет: {self.color}"
def load_cars_from_json():
try:
with open('bot_data.json', 'r', encoding='utf-8') as file:
data = json.load(file)
return [Car(**car) for car in data.get('cars', [])]
except FileNotFoundError:
return []
bot = telebot.TeleBot(API_TOKEN)
cars = load_cars_from_json()
@bot.message_handler(commands=['list_cars'])
def list_cars(message):
if cars:
response = "\n".join(str(car) for car in cars)
else:
response = "Машин нет в базе."
bot.reply_to(message, response)
bot.polling()utils/api_request.py
import requests
def fetch_data(url):
response = requests.get(url)
return response.json()utils/user_utils.py
import json
import sqlite3
def register_user_json(telegram_id, username):
data = init_json_db()
if not any(user['telegram_id'] == telegram_id for user in data['users']):
data['users'].append({'telegram_id': telegram_id, 'username': username})
with open('bot_data.json', 'w', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=4)
def register_user_sqlite(telegram_id, username):
conn = sqlite3.connect('bot.db')
cursor = conn.cursor()
cursor.execute("INSERT OR IGNORE INTO users (telegram_id, username) VALUES (?, ?)",
(telegram_id, username))
conn.commit()
conn.close()- Клонируйте репозиторий.
- Установите зависимости:
pip install pyTelegramBotAPI requests - Замените
YOUR_BOT_TOKENна токен вашего Telegram-бота. - Запустите скрипты настройки базы данных (
init_json_db()). - Добавьте тестовые данные в
bot_data.json:{ "users": [], "cars": [ {"id": 1, "model": "Toyota", "year": 2020, "color": "Red"}, {"id": 2, "model": "Honda", "year": 2018, "color": "Blue"} ] } - Запустите бот:
python bot/basic_bot.pyилиpython bot/car_example.py
- Получите токен бота у BotFather в Telegram.
- Используйте
sqlite_to_json()для экспорта данных SQLite в JSON. - Храните конфиденциальные данные в
.env(не включено).