Creating a Telegram bot with such functionality requires the use of the Telegram Bot API, a server to host your bot, and an SQLite database to store the information. Below, I'll provide you an example in Python using the python-telegram-bot library and sqlite3 for the database management. But remember, this is just an example, and deploying this bot requires careful handling to ensure it adheres to Telegram's policies and is secure.
import logging
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram import Bot
import sqlite3
# Initialize logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
# SQLite DB Helper Functions
def init_db():
conn = sqlite3.connect('user_data.db')
cur = conn.cursor()
# Create table if it does not exist
cur.execute('''CREATE TABLE IF NOT EXISTS users (user_id INTEGER PRIMARY KEY)''')
conn.commit()
conn.close()
def add_user_to_db(user_id):
conn = sqlite3.connect('user_data.db')
cur = conn.cursor()
cur.execute('INSERT OR IGNORE INTO users (user_id) VALUES (?)', (user_id,))
conn.commit()
conn.close()
def get_next_user():
conn = sqlite3.connect('user_data.db')
cur = conn.cursor()
cur.execute('SELECT user_id FROM users ORDER BY ROWID ASC LIMIT 1')
user = cur.fetchone()
conn.close()
return user[0] if user else None
def remove_user_from_db(user_id):
conn = sqlite3.connect('user_data.db')
cur = conn.cursor()
cur.execute('DELETE FROM users WHERE user_id = ?', (user_id,))
conn.commit()
conn.close()
# Bot Handlers
def start(update, context):
update.message.reply_text("Hello! I'm your group management bot.")
def message_handler(update, context):
user_id = update.message.from_user.id
# Check if user is not the admin
admin_status = context.bot.get_chat_administrators(update.message.chat_id)
is_admin = any(admin.user.id == user_id for admin in admin_status)
if not is_admin:
add_user_to_db(user_id)
def kick_handler(update, context):
chat_id = update.message.chat_id
user_id_to_kick = get_next_user()
if user_id_to_kick is not None:
try:
context.bot.kick_chat_member(chat_id, user_id_to_kick)
remove_user_from_db(user_id_to_kick)
update.message.reply_text(f"Kicked user with ID: {user_id_to_kick}")
except Exception as e:
logger.error(f"Failed to kick user: {e}")
update.message.reply_text("Failed to kick user.")
else:
update.message.reply_text("No users available to kick.")
def error(update, context):
"""
Log Errors caused by Updates.
"""
logger.warning('Update "%s" caused error "%s"', update, context.error)
def main():
# Initialize database
init_db()
# Create the Updater and pass it your bot's token.
token = 'YOUR_TELEGRAM_BOT_TOKEN'
updater = Updater(token, use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# On different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("kick", kick_handler))
# On non-command i.e message - add to database if not admin
dp.add_handler(MessageHandler(Filters.text & ~Filters.command, message_handler))
# Log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Run the bot until the user presses Ctrl-C or the process receives SIGINT, SIGTERM or SIGABRT
updater.idle()
if __name__ == '__main__':
main()
Before running the code, replace 'YOUR_TELEGRAM_BOT_TOKEN' with the actual token you get from BotFather.
This script will:
- Initialize a SQLite database if it does not exist.
- Add non-admin users to the database whenever they send a message.
- Kick a user when the
/kick command is called.
Please note:
- This script does not handle all scenarios, such as the bot being an admin or not, and checking for sufficient permissions.
- You may want to implement additional checks and features, such as confirming the action, scheduling, or permission handling.
- It's essential to comply with Telegram's Bot API terms of use and ensure that members of any group where this bot is deployed are fully aware of these features and have given consent to be part of the process.
Additionally, always remember to safely handle exceptions and edge cases in a production environment.
Lastly, be aware that indiscriminately kicking users could result in your bot being reported and potentially banned, so use such commands responsibly.