
Écrivons notre robot de modérateur de chat cool en Python. Laissez-le pouvoir nettoyer le chat, bannir les participants et leur donner des avertissements, saluer les nouveaux participants au chat et plus encore.
Nous allons créer un robot évolutif à part entière, en tenant compte des limites et des fonctionnalités de Telegram. Commençons par créer une structure de projet et apprendre au bot à répondre à des commandes simples.
Python , . Telethon Telegram API ( ) Databases SQLAlchemy Core ( ).
GitHub.

, , . 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('!')
Mais ce n'est pas pour ça que nous sommes venus ici. Nous voulons créer des équipes et d'autres fonctionnalités pour les administrateurs de groupe! Pour ce faire, nous devons être en mesure de faire la distinction entre les administrateurs et les membres ordinaires du groupe. Nous traiterons de cela dans la prochaine partie du didacticiel. Nous allons connecter la base de données et apprendre une manière intelligente d'obtenir des administrateurs.
À suivre.
Permettez-moi de vous rappeler que vous pouvez afficher le code résultant sur GitHub . Posez vos questions dans les commentaires. Sûrement moi ou quelqu'un d'autre y répondra. Et merci à vanutp pour les informations de base de l'article :)