Hardcore-Entwicklung fĂŒr Telegram. Do-it-yourself-Bot-Moderator. Teil 1

Lassen Sie uns unseren coolen Chat-Moderator-Bot in Python schreiben. Lassen Sie ihn in der Lage sein, den Chat aufzurĂ€umen, Teilnehmer zu sperren und ihnen Warnungen zu geben, neue Chat-Teilnehmer zu begrĂŒĂŸen und vieles mehr.





Wir werden einen vollwertigen skalierbaren Bot erstellen, der die Grenzen und Funktionen von Telegram berĂŒcksichtigt. Beginnen wir damit, eine Projektstruktur zu erstellen und dem Bot beizubringen, auf einfache Befehle zu reagieren.





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





GitHub.





Ein Beispiel fĂŒr die Arbeit eines zukĂŒnftigen Bots :)
:)

, , . 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('!')

      
      



Aber deshalb sind wir nicht hierher gekommen. Wir möchten Teams und andere Funktionen fĂŒr Gruppenadministratoren erstellen! Dazu mĂŒssen wir in der Lage sein, zwischen Administratoren und normalen Gruppenmitgliedern zu unterscheiden. Wir werden uns im nĂ€chsten Teil des Tutorials damit befassen. Wir werden die Datenbank verbinden und einen cleveren Weg finden, um Administratoren zu finden.





Fortsetzung folgt.






Ich möchte Sie daran erinnern, dass Sie den resultierenden Code auf GitHub anzeigen können . Stellen Sie Fragen in den Kommentaren. Sicher werde ich oder jemand anderes ihnen antworten. Und danke an vanutp fĂŒr die Hintergrundinformationen zum Artikel :)








All Articles