Hardcore development for Telegram. Do-it-yourself bot moderator. Part 1

Let's write our cool chat moderator bot in Python. Let him be able to clean up the chat, ban participants and give them warnings, greet new chat participants and more.





We will make a full-fledged scalable bot, taking into account the limits and features of Telegram. Let's start by creating a project structure and teaching the bot to respond to simple commands.





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





GitHub.





An example of the work of a future 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('!')

      
      



But that's not why we came here. We want to make teams and other features for group admins! To do this, we need to be able to distinguish between admins and ordinary group members. We will deal with this in the next part of the tutorial. We'll connect the database and learn a clever way to get admins.





To be continued.






Let me remind you that you can view the resulting code on GitHub . Ask any questions in the comments. Surely I or someone else will answer them. And thanks to vanutp for the background information for the article :)








All Articles