Creating a fully functional Telegram bot with the specifications you've provided is a comprehensive task. Below is a complete Python script using aiogram, SQLAlchemy, and sqlite3 that implements the core functionalities you requested. Due to the complexity and size, some parts are simplified, but this should serve as a solid foundation for further development.
Prerequisites
-
Install Required Libraries:
pip install aiogram sqlalchemy aiosqlite
-
Set Up Bot Token:
Replace 'YOUR_BOT_TOKEN_HERE' with your actual Telegram bot token.
Complete Python Code
import logging
from aiogram import Bot, Dispatcher, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.types import ParseMode, InlineKeyboardMarkup, InlineKeyboardButton
from aiogram.utils import executor
from sqlalchemy import create_engine, Column, Integer, String, Boolean, ForeignKey, DateTime, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from datetime import datetime, timedelta
import asyncio
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Initialize bot and dispatcher
API_TOKEN = 'YOUR_BOT_TOKEN_HERE'
bot = Bot(token=API_TOKEN)
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)
# Database setup
Base = declarative_base()
# Association table for many-to-many relationship between Config and Groups
config_groups = Table('config_groups', Base.metadata,
Column('config_id', Integer, ForeignKey('configs.id')),
Column('group_id', Integer, ForeignKey('groups.id'))
)
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
telegram_id = Column(Integer, unique=True, nullable=False)
is_admin = Column(Boolean, default=False)
license_key = Column(String, unique=True)
license_expiry = Column(DateTime)
class License(Base):
__tablename__ = 'licenses'
id = Column(Integer, primary_key=True)
key = Column(String, unique=True)
expires_at = Column(DateTime)
created_by = Column(Integer, ForeignKey('users.id'))
creator = relationship("User")
class Config(Base):
__tablename__ = 'configs'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'))
main_group = Column(String, nullable=False)
prompt_text = Column(String, default="Per favore, unisciti ai seguenti gruppi per essere sbloccato.")
media = Column(String, nullable=True) # URL or file_id
user = relationship("User")
groups = relationship("Group", secondary=config_groups, back_populates="configs")
class Group(Base):
__tablename__ = 'groups'
id = Column(Integer, primary_key=True)
chat_id = Column(String, unique=True, nullable=False)
name = Column(String)
configs = relationship("Config", secondary=config_groups, back_populates="groups")
# Initialize database
engine = create_engine('sqlite:///bot.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
# Utility functions
def is_admin(user_id: int) -> bool:
user = session.query(User).filter(User.telegram_id == user_id).first()
return user.is_admin if user else False
def generate_license_key():
return f"LIC-{datetime.now().timestamp()}"
async def check_user_subscriptions(user_id: int, config: Config):
try:
member = await bot.get_chat_member(config.main_group, user_id)
if member.status not in ['member', 'administrator', 'creator']:
raise Exception("Not a member")
except:
# User not in main group
return False, config.groups
# Check secondary groups
not_in = []
for group in config.groups:
try:
member = await bot.get_chat_member(group.chat_id, user_id)
if member.status not in ['member', 'administrator', 'creator']:
not_in.append(group)
except:
not_in.append(group)
return len(not_in) == 0, not_in
# Handlers
@dp.message_handler(commands=['start'])
async def cmd_start(message: types.Message):
user = session.query(User).filter(User.telegram_id == message.from_user.id).first()
if not user:
user = User(telegram_id=message.from_user.id)
session.add(user)
session.commit()
# Check license
if user.license_expiry and user.license_expiry < datetime.now():
await message.reply("La tua licenza è scaduta. Per favore, contatta un amministratore.")
return
await message.reply("Benvenuto nel bot! Usa /help per vedere i comandi disponibili.")
@dp.message_handler(commands=['help'])
async def cmd_help(message: types.Message):
help_text = (
"Comandi disponibili:\n"
"/start - Inizia a usare il bot\n"
"/help - Mostra questo messaggio\n"
)
if is_admin(message.from_user.id):
help_text += (
"/add_admin - Aggiungi un amministratore\n"
"/remove_admin - Rimuovi un amministratore\n"
"/generate_license - Genera una licenza\n"
"/manage_config - Gestisci configurazioni\n"
)
await message.reply(help_text)
# Admin commands
@dp.message_handler(commands=['add_admin'])
async def cmd_add_admin(message: types.Message):
if not is_admin(message.from_user.id):
await message.reply("Non sei un amministratore.")
return
args = message.get_args()
if not args:
await message.reply("Usa /add_admin <user_id>")
return
try:
user_id = int(args.strip())
user = session.query(User).filter(User.telegram_id == user_id).first()
if not user:
user = User(telegram_id=user_id, is_admin=True)
session.add(user)
else:
user.is_admin = True
session.commit()
await message.reply(f"Utente {user_id} è ora un amministratore.")
except ValueError:
await message.reply("ID utente non valido.")
@dp.message_handler(commands=['remove_admin'])
async def cmd_remove_admin(message: types.Message):
if not is_admin(message.from_user.id):
await message.reply("Non sei un amministratore.")
return
args = message.get_args()
if not args:
await message.reply("Usa /remove_admin <user_id>")
return
try:
user_id = int(args.strip())
user = session.query(User).filter(User.telegram_id == user_id).first()
if not user:
await message.reply("Utente non trovato.")
return
user.is_admin = False
session.commit()
await message.reply(f"Utente {user_id} non è più un amministratore.")
except ValueError:
await message.reply("ID utente non valido.")
@dp.message_handler(commands=['generate_license'])
async def cmd_generate_license(message: types.Message):
if not is_admin(message.from_user.id):
await message.reply("Non sei un amministratore.")
return
args = message.get_args().split()
if len(args) < 2:
await message.reply("Usa /generate_license <user_id> <days>")
return
try:
user_id = int(args[0])
days = int(args[1])
user = session.query(User).filter(User.telegram_id == user_id).first()
if not user:
await message.reply("Utente non trovato.")
return
license_key = generate_license_key()
expiry = datetime.now() + timedelta(days=days)
license = License(key=license_key, expires_at=expiry, creator=session.query(User).filter(User.telegram_id == message.from_user.id).first())
session.add(license)
user.license_key = license_key
user.license_expiry = expiry
session.commit()
await message.reply(f"Licenza generata: {license_key}, scade il {expiry.strftime('%d/%m/%Y')}")
except ValueError:
await message.reply("Parametri non validi.")
@dp.message_handler(commands=['manage_config'])
async def cmd_manage_config(message: types.Message):
if not is_admin(message.from_user.id):
await message.reply("Non sei un amministratore.")
return
keyboard = InlineKeyboardMarkup(row_width=1)
keyboard.add(
InlineKeyboardButton("Aggiungi Configurazione", callback_data="add_config"),
InlineKeyboardButton("Rimuovi Configurazione", callback_data="remove_config"),
InlineKeyboardButton("Visualizza Configurazioni", callback_data="view_configs")
)
await message.reply("Scegli un'azione per la configurazione:", reply_markup=keyboard)
@dp.callback_query_handler(lambda c: c.data and c.data.startswith('add_config'))
async def process_add_config(callback_query: types.CallbackQuery):
await callback_query.answer()
# This is a placeholder. Implement FSM to collect configuration details.
await bot.send_message(callback_query.from_user.id, "Aggiungere una nuova configurazione non è ancora implementato.")
@dp.callback_query_handler(lambda c: c.data and c.data.startswith('remove_config'))
async def process_remove_config(callback_query: types.CallbackQuery):
await callback_query.answer()
# Placeholder for removing configuration
await bot.send_message(callback_query.from_user.id, "Rimuovere una configurazione non è ancora implementato.")
@dp.callback_query_handler(lambda c: c.data and c.data.startswith('view_configs'))
async def process_view_configs(callback_query: types.CallbackQuery):
await callback_query.answer()
user = session.query(User).filter(User.telegram_id == callback_query.from_user.id).first()
if not user:
await bot.send_message(callback_query.from_user.id, "Nessuna configurazione trovata.")
return
configs = session.query(Config).filter(Config.user_id == user.id).all()
if not configs:
await bot.send_message(callback_query.from_user.id, "Nessuna configurazione trovata.")
return
for config in configs:
groups = ", ".join([group.name for group in config.groups])
await bot.send_message(callback_query.from_user.id, f"Configurazione {config.id}:\nMain Group: {config.main_group}\nGruppi Secondari: {groups}")
# Middleware to handle new members in main groups
@dp.chat_member_handler()
async def on_chat_member_update(update: types.ChatMemberUpdated):
new_status = update.new_chat_member.status
user_id = update.from_user.id
chat_id = update.chat.id
# Check if this chat is a main group in any configuration
configs = session.query(Config).filter(Config.main_group == chat_id).all()
for config in configs:
if new_status in ['member', 'administrator', 'creator']:
is_subscribed, not_in_groups = await check_user_subscriptions(user_id, config)
if not is_subscribed:
# Mute the user
try:
await bot.restrict_chat_member(chat_id, user_id, permissions=types.ChatPermissions(can_send_messages=False))
except Exception as e:
logger.error(f"Error muting user: {e}")
# Send prompt message
subscribed = []
not_subscribed = []
for group in config.groups:
try:
member = await bot.get_chat_member(group.chat_id, user_id)
if member.status in ['member', 'administrator', 'creator']:
subscribed.append(group)
else:
not_subscribed.append(group)
except:
not_subscribed.append(group)
text = config.prompt_text + "\n"
for group in config.groups:
status = "✔️" if group in subscribed else "❌"
text += f"{status} [{group.name}](https://t.me/{group.chat_id})\n"
keyboard = InlineKeyboardMarkup()
keyboard.add(InlineKeyboardButton("Riprova", callback_data=f"retry_{config.id}_{user_id}"))
if config.media:
await bot.send_photo(chat_id, config.media, caption=text, parse_mode=ParseMode.MARKDOWN, reply_markup=keyboard)
else:
await bot.send_message(chat_id, text, parse_mode=ParseMode.MARKDOWN, reply_markup=keyboard)
@dp.callback_query_handler(lambda c: c.data and c.data.startswith('retry_'))
async def process_retry(callback_query: types.CallbackQuery):
await callback_query.answer()
_, config_id, user_id = callback_query.data.split('_')
config = session.query(Config).filter(Config.id == config_id).first()
if not config:
await bot.send_message(callback_query.from_user.id, "Configurazione non trovata.")
return
is_subscribed, not_in_groups = await check_user_subscriptions(int(user_id), config)
if is_subscribed:
# Unmute the user
try:
await bot.restrict_chat_member(config.main_group, int(user_id), permissions=types.ChatPermissions(can_send_messages=True))
await bot.send_message(config.main_group, f"Utente {user_id} è stato sbloccato.")
except Exception as e:
logger.error(f"Error unmuting user: {e}")
else:
await bot.send_message(callback_query.from_user.id, "Non hai ancora tutti i gruppi necessari iscritti.")
# Error handler
@dp.errors_handler()
async def global_error_handler(update, exception):
logger.exception(f"Update: {update} caused error: {exception}")
return True # Errors are handled
# Periodic task to check if bot is still admin in all groups
async def check_bot_admin_status():
while True:
try:
groups = session.query(Group).all()
for group in groups:
try:
member = await bot.get_chat_member(group.chat_id, (await bot.get_me()).id)
if member.status not in ['administrator', 'creator']:
logger.warning(f"Il bot non è più amministratore di {group.name}")
# Notify admin or take action
except Exception as e:
logger.error(f"Errore nel controllare lo status del bot in {group.name}: {e}")
except Exception as e:
logger.error(f"Errore nel task di controllo admin: {e}")
await asyncio.sleep(3600) # Check every hour
# Startup and shutdown
async def on_startup(dp):
asyncio.create_task(check_bot_admin_status())
if __name__ == '__main__':
executor.start_polling(dp, on_startup=on_startup)
Explanation of the Code
-
Imports and Setup:
- Imported necessary libraries including
aiogram for the bot, SQLAlchemy for ORM, and other utilities.
- Configured logging for debugging purposes.
- Initialized the bot with a token and set up the dispatcher with in-memory storage.
-
Database Models:
- Defined
User, License, Config, and Group models using SQLAlchemy.
- Established relationships between these models, such as many-to-many for configurations and groups.
-
Utility Functions:
is_admin: Checks if a user is an administrator.
generate_license_key: Generates a simple license key based on the current timestamp.
check_user_subscriptions: Checks if a user is subscribed to all required groups.
-
Command Handlers:
/start: Registers the user and checks license validity.
/help: Displays available commands based on user roles.
/add_admin and /remove_admin: Allow administrators to manage other admins.
/generate_license: Allows admins to generate licenses for users.
/manage_config: Provides an interface to manage configurations with inline buttons.
-
Configuration Management:
- Placeholders for adding and removing configurations. Implementing Full FSM for creating configurations would require additional code.
-
Chat Member Handler:
- Monitors when users join main groups.
- Checks if they are part of all required secondary groups.
- Mutes them and sends a prompt if they are not part of all required groups.
- Provides a "Retry" button to recheck memberships.
-
Callback Query Handlers:
- Handles button presses like retrying group checks.
-
Error Handling:
- Global error handler to log exceptions.
-
Periodic Task:
- Periodically checks if the bot remains an admin in all configured groups.
Notes and Further Development
-
FSM for Configuration:
The process_add_config and related functions are placeholders. Implementing a Finite State Machine (FSM) using aiogram's Dispatcher would allow collecting detailed configuration data from admins interactively.
-
License Validation:
Currently, license validation is basic. You might want to implement more robust features, such as different license tiers.
-
Admin Notifications:
When the bot is removed from a group’s admin list, it logs a warning. You might want to notify administrators directly through Telegram.
-
Enhanced Error Handling:
While a global error handler is present, more granular error handling can be implemented for specific actions.
-
Localization:
All user-facing texts are in Italian as per your requirement, but ensure consistency and handle edge cases where translations might be needed.
-
Security:
Ensure that only authorized administrators can perform admin actions. Validate inputs thoroughly to prevent SQL injections or other malicious activities.
-
Media Handling:
The media field in the Config model expects a URL or file_id. Ensure that media is correctly uploaded and accessible.
-
Database Migrations:
For production use, consider using database migration tools like Alembic to handle schema changes gracefully.
-
Scalability:
For larger user bases, consider switching to a more robust database system like PostgreSQL.
-
Testing:
Rigorously test each functionality, especially group membership checks and permission settings, as Telegram’s API can have limitations and specific behaviors.
Conclusion
This script provides a foundational structure for your Telegram bot with user roles, license management, and group subscription checks. Depending on your specific needs and further requirements, you may need to expand and refine this code. Ensure you handle all edge cases and test thoroughly in a controlled environment before deploying to production.