import sqlite3 import schedule import time from aiogram import executor, types from aiogram.dispatcher.filters import AdminFilter, IsReplyFilter, Text from config import adminId from misc import bot, dp # Send admin message about bot started async def send_adm(dp): await bot.send_message(chat_id=adminId, text='Bot started!') # info tour @dp.message_handler(commands=['start']) async def welcome_send_info(message: types.Message): await message.answer(f"✳ Приветствую,{message.from_user.full_name}! ✳\n\n" f"Бот принадлежит чату - \n\n" # f"\n\n" f" \n\n") # f" \n" # f" \n" # f" \n" # f" \n" # f" \n" # f" \n" # f" \n" # Приветственное сообщение для нового пользователя чата @dp.message_handler(content_types=["new_chat_members"]) async def new_chat_member(message: types.Message): chat_id = message.chat.id await bot.delete_message(chat_id=chat_id, message_id=message.message_id) await bot.send_message(chat_id=chat_id, text=f"Добро пожаловать в наш чат! " f" [{message.new_chat_members[0].full_name}]" f"(tg://user?id={message.new_chat_members[0].id})" f"\nОбязательно ознакомься с правилами!" , parse_mode=types.ParseMode.MARKDOWN) # delete message user leave chat @dp.message_handler(content_types=["left_chat_member"]) async def leave_chat(message: types.Message): await bot.delete_message(chat_id=message.chat.id, message_id=message.message_id) @dp.message_handler(commands=['warn', 'варн'], commands_prefix='!/.') async def warnUser(message: types.Message): if message.chat.type in ['group', 'supergroup']: try: list_admins = await message.chat.get_administrators() from_user = message['from']['id'] list_admins_2 = [] for admin in list_admins: list_admins_2.append(admin['user']['id']) for admin in list_admins: if int(admin) == int(from_user): if not message.reply_to_message: await message.answer("Отправь эту команду ответом на сообщение нарушителя.") else: tg_id = message['reply_to_message']['from']['id'] first_name = message['reply_to_message']['from']['first_name'] connect = sqlite3.connect('warn_list.db') cursor = connect.cursor() cursor.execute("""CREATE TABLE IF NOT EXISTS warn_list( id INTEGER )""") connect.commit() people_id = message.chat.id cursor.execute(f"SELECT id FROM warn_list WHERE id = {people_id}") data = cursor.rowcount() if data < 3: user_id = [message.reply_to_message.from_user.id] cursor.execute("INSERT INTO warn_list VALUES(?);", user_id) connect.commit() else: # Здесь выбирайте сами - давать мут или бан # Затем можно удалить все варны пользователя cursor.execute(f"DELETE FROM warn_list WHERE id = {people_id}") connect.commit() if from_user not in list_admins_2: await message.answer("Эту команду могут использовать только админы чата.") except TypeError: pass else: await message.answer('Эта команда предназначена для использования в групповых чатах, а не в личных сообщениях!') # Функция автопостинга (В разработке) @dp.message_handler(AdminFilter(is_chat_admin=True), IsReplyFilter(is_reply=False), commands=['rec'], commands_prefix='!', chat_type=[types.ChatType.SUPERGROUP, types.ChatType.GROUP]) async def rec(message: types.Message): chat_id = ' ID ' await bot.send_message(chat_id=chat_id, text=f" . ", parse_mode=types.ParseMode.MARKDOWN) await bot.delete_message(chat_id=message.chat.id, message_id=message.message_id) schedule.every(1).minutes.do(rec) # Функция проверки работоспособности бота (Особого функционала нет, лишь для проверки старта бота) @dp.message_handler(AdminFilter(is_chat_admin=True), IsReplyFilter(is_reply=False), commands=['статус'], commands_prefix='!', chat_type=[types.ChatType.SUPERGROUP, types.ChatType.GROUP]) async def status(message: types.Message): chat_id = ' ID ' await bot.send_message(chat_id=chat_id, text=f" Бот полностью функционирует. ", parse_mode=types.ParseMode.MARKDOWN) await bot.delete_message(chat_id=message.chat.id, message_id=message.message_id) # Функция для показа информации о пользователе. (Пользователь запрашивает информацию о себе) @dp.message_handler(chat_type=[types.ChatType.SUPERGROUP, types.ChatType.GROUP], commands=['инфо'],commands_prefix='!') async def welcome(message: types.Message): if message.from_user.username is None: await message.reply(f"Имя - {message.from_user.full_name}\nID - {message.from_user.id}\n") else: await message.reply(f"Имя - {message.from_user.full_name}\n\n" f"ID - <code>{message.from_user.id}</code>\n\n" f"Тег - @{message.from_user.username}\n\n") # Функция блокировки @dp.message_handler(AdminFilter(is_chat_admin=True), IsReplyFilter(is_reply=True), commands=['бан'], commands_prefix='!', chat_type=[types.ChatType.SUPERGROUP, types.ChatType.GROUP]) async def ban(message: types.Message): replied_user = message.reply_to_message.from_user.id admin_id = message.from_user.id await bot.kick_chat_member(chat_id=message.chat.id, user_id=replied_user) await bot.delete_message(chat_id=message.chat.id, message_id=message.message_id) await bot.send_message(chat_id=message.chat.id, text=f"[{message.reply_to_message.from_user.full_name}]" f"(tg://user?id={replied_user})" f" был забанен администрацией ", parse_mode=types.ParseMode.MARKDOWN) # Функция мута пользователя в чате @dp.message_handler(AdminFilter(is_chat_admin=True), IsReplyFilter(is_reply=True), commands=['мут'], commands_prefix='!', chat_type=[types.ChatType.SUPERGROUP, types.ChatType.GROUP]) async def mute(message: types.Message): args = message.text.split() if len(args) > 1: till_date = message.text.split()[1] else: till_date = "15m" if till_date[-1] == "м": ban_for = int(till_date[:-1]) * 60 elif till_date[-1] == "ч": ban_for = int(till_date[:-1]) * 3600 elif till_date[-1] == "д": ban_for = int(till_date[:-1]) * 86400 else: ban_for = 15 * 60 replied_user = message.reply_to_message.from_user.id now_time = int(time.time()) await bot.restrict_chat_member(chat_id=message.chat.id, user_id=replied_user, permissions=types.ChatPermissions(can_send_messages=False, can_send_media_messages=False, can_send_other_messages=False), until_date=now_time + ban_for) await bot.delete_message(chat_id=message.chat.id, message_id=message.message_id) await bot.send_message(text=f"[{message.reply_to_message.from_user.full_name}](tg://user?id={replied_user})" f" выдан мут на {till_date}", chat_id=message.chat.id, parse_mode=types.ParseMode.MARKDOWN) # Функция снятия мута с пользователя в чате @dp.message_handler(AdminFilter(is_chat_admin=True), IsReplyFilter(is_reply=True), commands_prefix='!', chat_type=[types.ChatType.SUPERGROUP, types.ChatType.GROUP], commands=['смут']) async def unmute(message: types.Message): replied_user = message.reply_to_message.from_user.id await bot.restrict_chat_member(chat_id=message.chat.id, user_id=replied_user, permissions=types.ChatPermissions(can_send_messages=True, can_send_media_messages=True, can_send_other_messages=True), ) await bot.delete_message(chat_id=message.chat.id, message_id=message.message_id) await bot.send_message(text=f"[{message.reply_to_message.from_user.full_name}](tg://user?id={replied_user})" f" мут снят", chat_id=message.chat.id, parse_mode=types.ParseMode.MARKDOWN) # pin chat message Далее не нужные команды # @dp.message_handler(AdminFilter(is_chat_admin=True), IsReplyFilter(is_reply=True), # chat_type=[types.ChatType.SUPERGROUP, types.ChatType.GROUP], commands=['pin'], commands_prefix='!') # async def pin_message(message: types.Message): # msg_id = message.reply_to_message.message_id # await bot.pin_chat_message(message_id=msg_id, chat_id=message.chat.id) # unpin chat message # @dp.message_handler(AdminFilter(is_chat_admin=True), IsReplyFilter(is_reply=True), commands_prefix='!', # chat_type=[types.ChatType.SUPERGROUP, types.ChatType.GROUP], commands=['unpin']) # async def unpin_message(message: types.Message): # msg_id = message.reply_to_message.message_id # await bot.unpin_chat_message(message_id=msg_id, chat_id=message.chat.id) # unpin all pins # @dp.message_handler(AdminFilter(is_chat_admin=True), IsReplyFilter(is_reply=True), commands_prefix='!', # chat_type=[types.ChatType.SUPERGROUP, types.ChatType.GROUP], commands=['unpin_all']) # async def unpin_all_messages(message: types.Message): # await bot.unpin_all_chat_messages(chat_id=message.chat.id) # delete user message # @dp.message_handler(AdminFilter(is_chat_admin=True), IsReplyFilter(is_reply=True), commands_prefix='!', # chat_type=[types.ChatType.SUPERGROUP, types.ChatType.GROUP], commands=['del']) # async def delete_message(message: types.Message): # msg_id = message.reply_to_message.message_id # await bot.delete_message(chat_id=message.chat.id, message_id=msg_id) # await bot.delete_message(chat_id=message.chat.id, message_id=message.message_id) # Функция для получения списка администраторов. (Указывает лишь администраторов чата, IRIS и прочее не видет) @dp.message_handler(chat_type=[types.ChatType.SUPERGROUP, types.ChatType.GROUP], commands=['admins'], commands_prefix='!/') async def get_admin_list(message: types.Message): admins_id = [(admin.user.id, admin.user.full_name) for admin in await bot.get_chat_administrators( chat_id=message.chat.id)] admins_list = [] for ids, name in admins_id: admins_list.append("".join(f"[{name}](tg://user?id={ids})")) result_list = "" for admins in admins_list: result_list += "".join(admins) + '\n' await message.reply("Администрация :\n" + result_list, parse_mode=types.ParseMode.MARKDOWN) # Функция репорта на пользователя с отправкой сообщения администратору. (Возможно отправляет сообщение всем администраторам чата. Требует проверки) @dp.message_handler(chat_type=[types.ChatType.SUPERGROUP, types.ChatType.GROUP], commands=['report'], commands_prefix='!/') async def report_by_user(message: types.Message): msg_id = message.reply_to_message.message_id user_id = message.from_user.id admins_list = [admin.user.id for admin in await bot.get_chat_administrators(chat_id=message.chat.id)] for adm_id in admins_list: try: await bot.send_message(text=f"User: [{message.from_user.full_name}](tg://user?id={user_id})\n" f"Reported about next message:\n" f"[Возможное нарушение](t.me/{message.chat.username}/{msg_id})", chat_id=adm_id, parse_mode=types.ParseMode.MARKDOWN, disable_web_page_preview=True) except: pass await message.reply("Сообщение отправлено Адмнистрации") # Функция автоматического удаления ссылок, тегов, а так же доп. фильтр слов (Фильтр слов нужно переделать, выглядит слишком криво и масштабно) @dp.message_handler(content_types=['text']) async def delete_links(message: types.Message): admins_list = [admin.user.id for admin in await bot.get_chat_administrators(chat_id=message.chat.id)] if message.from_user.id not in admins_list: if '@' in message.text: await bot.delete_message(message.chat.id, message.message_id) for entity in message.entities: if entity.type in ["url", "text_link"]: await bot.delete_message(message.chat.id, message.message_id) if 'Чит' in message.text: await bot.delete_message(message.chat.id, message.message_id) if 'чит' in message.text: await bot.delete_message(message.chat.id, message.message_id) if 'Читы' in message.text: await bot.delete_message(message.chat.id, message.message_id) if 'читы' in message.text: await bot.delete_message(message.chat.id, message.message_id) if 'Читу' in message.text: await bot.delete_message(message.chat.id, message.message_id) if 'читу' in message.text: await bot.delete_message(message.chat.id, message.message_id) if 'Читами' in message.text: await bot.delete_message(message.chat.id, message.message_id) if 'читами' in message.text: await bot.delete_message(message.chat.id, message.message_id) if 'Читом' in message.text: await bot.delete_message(message.chat.id, message.message_id) if 'читом' in message.text: await bot.delete_message(message.chat.id, message.message_id) # Polling if __name__ == '__main__': executor.start_polling(dp, on_startup=send_adm, skip_updates=True)
Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.
OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.
import sys
name = sys.stdin.readline()
print("Hello "+ name)
Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.
When ever you want to perform a set of operations based on a condition IF-ELSE is used.
if conditional-expression
#code
elif conditional-expression
#code
else:
#code
Indentation is very important in Python, make sure the indentation is followed correctly
For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.
mylist=("Iphone","Pixel","Samsung")
for i in mylist:
print(i)
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while condition
#code
There are four types of collections in Python.
List is a collection which is ordered and can be changed. Lists are specified in square brackets.
mylist=["iPhone","Pixel","Samsung"]
print(mylist)
Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
Below throws an error if you assign another value to tuple again.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)
Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.
myset = {"iPhone","Pixel","Samsung"}
print(myset)
Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.
mydict = {
"brand" :"iPhone",
"model": "iPhone 11"
}
print(mydict)
Following are the libraries supported by OneCompiler's Python compiler
Name | Description |
---|---|
NumPy | NumPy python library helps users to work on arrays with ease |
SciPy | SciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation |
SKLearn/Scikit-learn | Scikit-learn or Scikit-learn is the most useful library for machine learning in Python |
Pandas | Pandas is the most efficient Python library for data manipulation and analysis |
DOcplex | DOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling |