Готовые примеры
Готовые примеры
Эхо-бот
import asyncio
from pykodaribot import Bot, Dispatcher, filters
bot = Bot("bot_ВАШ_ТОКЕН")
dp = Dispatcher()
@dp.message(filters.command("start"))
async def start(msg):
await msg.answer("Привет! Пришли мне что-нибудь, я повторю.")
@dp.message()
async def echo(msg):
if msg.text:
await msg.reply(msg.text)
elif msg.media_url:
await msg.answer(f"Получил {msg.media_type}: {msg.media_name or 'файл'}")
asyncio.run(dp.start_polling(bot))
Бот с меню команд и кнопками
import asyncio
from pykodaribot import (Bot, BotCommand, Dispatcher, InlineKeyboardButton,
InlineKeyboardMarkup, filters)
bot = Bot("bot_ВАШ_ТОКЕН")
dp = Dispatcher()
MENU = InlineKeyboardMarkup(inline_keyboard=[
[InlineKeyboardButton(text="📅 Расписание", callback_data="menu:schedule")],
[InlineKeyboardButton(text="❓ Помощь", callback_data="menu:help")],
])
@dp.message(filters.command("start", "menu"))
async def menu(msg):
await msg.answer("Что показать?", reply_markup=MENU)
@dp.callback_query(filters.callback_data_prefix("menu:"))
async def on_menu(cb):
await cb.answer()
section = cb.data.split(":")[1]
text = "Расписание пока пустое" if section == "schedule" else "Напишите /menu"
await bot.edit_message_text(cb.message.chat.id, cb.message.message_id, text, reply_markup=MENU)
async def main():
await bot.set_my_commands([
BotCommand("start", "Начать работу"),
BotCommand("menu", "Открыть меню"),
])
await dp.start_polling(bot)
asyncio.run(main())
Модератор группы
import asyncio
from pykodaribot import Bot, BotError, Dispatcher, filters
bot = Bot("bot_ВАШ_ТОКЕН")
dp = Dispatcher()
BAN_WORDS = ("казино", "ставки")
@dp.message()
async def guard(msg):
if not msg.text:
return
if any(w in msg.text.lower() for w in BAN_WORDS):
try:
await bot.delete_message(msg.chat.id, msg.message_id)
await bot.kick_chat_member(msg.chat.id, msg.from_user.id)
except BotError as e:
print("Не хватило прав:", e.description)
@dp.message(filters.command("pin"))
async def pin(msg):
if msg.reply_to_message_id:
await bot.pin_message(msg.chat.id, msg.reply_to_message_id)
await msg.answer("Закреплено")
asyncio.run(dp.start_polling(bot))
Рассылка уведомлений
Бот с флагом can_initiate_chat открывает диалог сам:
import asyncio
from pykodaribot import Bot, BotError
bot = Bot("bot_ВАШ_ТОКЕН")
async def notify(student_id: str, text: str) -> bool:
try:
chat = await bot.get_or_create_chat(student_id)
await bot.send_message(chat["chat_id"], text)
return True
except BotError as e:
print(student_id, e.error_code, e.description)
return False
async def main():
students = ["100500", "100501", "100502"]
for sid in students:
await notify(sid, "Занятие перенесено на 18:00")
await asyncio.sleep(2)
await bot.close()
asyncio.run(main())
Пауза между отправками нужна из-за лимита 30 сообщений в минуту.
Отправка отчёта файлом
import asyncio
from pathlib import Path
from pykodaribot import Bot
async def main():
async with Bot("bot_ВАШ_ТОКЕН") as bot:
await bot.send_document(chat_id=123, media=Path("report.pdf"),
caption="Отчёт за май")
asyncio.run(main())
20 просмотров