Desarrollo incondicional para Telegram. Moderador de bot de bricolaje. Parte 1

Escribamos nuestro genial bot moderador de chat en Python. Permítale limpiar el chat, prohibir a los participantes y darles advertencias, saludar a los nuevos participantes del chat y más.





Haremos un bot escalable en toda regla, teniendo en cuenta los límites y características de Telegram. Comencemos por crear una estructura de proyecto y enseñarle al bot a responder a comandos simples.





Python , . Telethon Telegram API ( ) Databases SQLAlchemy Core ( ).





GitHub.





Un ejemplo del trabajo de un futuro bot :)
:)

, , . BotFather.





. " 2077", — .





Telegram API

", -" , Telegram API Telegram Bot API.





Bot API : , . , Telegram API. , : , , - , - API. .





, Telegram API Telethon:





$ pip install telethon
      
      



Telegram API , my.telegram.org. , API .





. api_id api_hash "". .





:





app/
    __init__.py
    __main__.py
    handlers.py
config.py
      
      



handlers.py



— .





config.py



. :





BOT_TOKEN = '--'
API_ID = 123456789
API_HASH = '-'
      
      



, . config.





, __init__.py



. , telethon — TelegramClient



. .





( id, ). , TelegramClient:





import logging
from telethon import TelegramClient
import config

class Bot(TelegramClient):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.me = None  #     

#  ,   API
bot = Bot('bot', config.API_ID, config.API_HASH)
      
      



. . ( 'bot'



: .)





parse_mode



— . ( , , ). HTML.





:





bot.parse_mode = 'HTML'
logging.basicConfig(level=logging.INFO)
      
      



bot , : app.handlers ( ).





import app.handlers
      
      



, .





async def start():
    #   
    await bot.connect()
    
    #   .  sign_in    .      bot.me
    bot.me = await bot.sign_in(bot_token=config.BOT_TOKEN)
    
    #         
    await bot.run_until_disconnected()

      
      



, , run, start:





def run():
    bot.loop.run_until_complete(start())
      
      



__init__.py
import logging

from telethon import TelegramClient

import config


class Bot(TelegramClient):
    def __init__(self, *args):
        super().__init__(*args)
        self.me = None


bot = Bot('bot', config.API_ID, config.API_HASH)
bot.parse_mode = 'HTML'
logging.basicConfig(level=logging.INFO)

import app.handlers


async def start():
    await bot.connect()
    bot.me = await bot.sign_in(bot_token=config.BOT_TOKEN)
    await bot.run_until_disconnected()


def run():
    bot.loop.run_until_complete(start())

      
      



.





, handlers.py . .





? ( " ", " ", " " ). :

) ,

) , - ,

) ,

, . : ", !"





, telethon.events.ChatAction.





:





from telethon import events

from app import bot

@bot.on(events.ChatAction())
async def on_join(event: events.ChatAction.Event):
    if event.is_group and event.user_added and event.user_id == bot.me.id:
				await bot.send_message(event.chat.id, ', !')
      
      



@bot.on



. " ". , .





__main__.py



run:





from app import run

run()
      
      



! .





$ python -m app
      
      



:





@bot.on(events.ChatAction(func=lambda e: e.is_group and e.user_added and e.user_id == bot.me.id))
async def on_join(event: events.ChatAction.Event):
    await event.respond(', !')
      
      



ChatAction func



— . . .





event.respond



. , event. bot.send_message



, .





, , ! . :





, " ?":





...
from telethon.tl.custom import Message
...

@bot.on(events.NewMessage(func=lambda e: e.text.lower() == ' ?'))
async def who_are_you(event: Message):
    await event.respond(' , ,        !')

      
      



Message — NewMessage.





--, privacy mode.





, /cat.





...
from telethon.tl.custom import Message
...

@bot.on(events.NewMessage(func=lambda e: e.text.lower() == '/cat'))
async def send_cat(event: Message):
    await bot.send_message(event.chat.id, file='path/to/cat.png')

      
      



, bot.upload_file() .





, /dice ( )





...
from telethon.tl.custom import Message
from telethon.tl.types import InputMediaDice
...

@bot.on(events.NewMessage(func=lambda e: e.text.lower() == '/dice'))
async def send_dice(event: Message):
    await bot.send_message(event.chat.id, file=InputMediaDice('?'))
      
      



, , :





@bot.on(events.ChatAction(func=lambda e: (e.user_added or e.user_joined) and e.user_id != bot.me.id))
async def greet(event: events.ChatAction.Event):
    await event.respond('!')

      
      



Pero no es por eso que vinimos aquí. ¡Queremos crear equipos y otras funciones para administradores de grupos! Para hacer esto, necesitamos poder distinguir entre administradores y miembros ordinarios del grupo. Trataremos de esto en la siguiente parte del tutorial. Conectaremos la base de datos y aprenderemos una forma inteligente de conseguir administradores.





Continuará.






Permítame recordarle que puede ver el código resultante en GitHub . Haga cualquier pregunta en los comentarios. Seguramente yo o alguien más les responderemos. Y gracias a vanutp por la información de fondo del artículo :)








All Articles