Advertisement
FanaticExplorer

telegram_bot_api

Apr 21st, 2024
788
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.64 KB | Source Code | 0 0
  1. # Сервер розвернув на vps, ось таким чином:
  2. # https://github.com/aiogram/telegram-bot-api/tree/master/example
  3.  
  4. # Мій код:
  5. import os
  6. from pathlib import Path
  7. from datetime import datetime
  8.  
  9. import asyncio
  10. from loguru import logger
  11.  
  12. from aiogram import Bot, Dispatcher, types, F, Router
  13. from aiogram.types import FSInputFile, ErrorEvent
  14. from aiogram.filters import Command
  15. from aiogram.utils.chat_action import ChatActionSender
  16. from aiogram.utils.keyboard import InlineKeyboardBuilder
  17. from aiogram.client.session.aiohttp import AiohttpSession
  18. from aiogram.client.telegram import TelegramAPIServer
  19.  
  20. from corrupt import corrupt_file
  21.  
  22.  
  23. def create_dated_log_dir(base_dir="logs"):
  24.     """Creates a directory structure for daily logs within the base directory.
  25.  
  26.    Args:
  27.        base_dir (str, optional): The base directory for logs. Defaults to "logs".
  28.    """
  29.     today_str = datetime.utcnow().strftime("%Y-%m-%d")
  30.     dated_dir = f"{base_dir}/{today_str}"
  31.     if not os.path.exists(dated_dir):
  32.         os.makedirs(dated_dir)
  33.     return dated_dir
  34.  
  35.  
  36. Path("logs").mkdir(parents=True, exist_ok=True)
  37. logger.add(f"{create_dated_log_dir()}/{{time:HH-mm-ss}}.log",)
  38.  
  39. bot_token = os.environ.get('BOT_TOKEN')
  40. if not bot_token:
  41.     raise ValueError("BOT_TOKEN environment variable is not set")
  42. api_server = os.environ.get('API_SERVER')
  43. if not api_server:
  44.     raise ValueError("API_SERVER environment variable is not set")
  45.  
  46.  
  47. session = AiohttpSession(api=TelegramAPIServer.from_base(api_server))
  48.  
  49. bot = Bot(token=bot_token, session=session)
  50. dp = Dispatcher()
  51. router = Router()
  52. dp.startup.register(lambda: logger.info("Bot have been started"))
  53. dp.shutdown.register(lambda: logger.info("Bot have been stopped"))
  54.  
  55. files_dir = Path("files")
  56. files_dir.mkdir(parents=True, exist_ok=True)
  57.  
  58.  
  59. @router.message(F.document)
  60. async def file_handler(message: types.Message):
  61.     status = await message.answer("📥 Downloading file...")
  62.     file_path = Path(files_dir / message.document.file_name)
  63.  
  64.     await bot.download(message.document, file_path)
  65.     await status.edit_text("👾 Corrupting file...")
  66.     corrupted_file_path = await corrupt_file(str(file_path))
  67.  
  68.     if file_path.exists():
  69.         file_path.unlink()
  70.  
  71.     Path(corrupted_file_path).rename(file_path)
  72.     await status.edit_text("📤 Sending file...")
  73.     async with ChatActionSender.upload_document(bot=bot, chat_id=message.chat.id):
  74.         await message.reply_document(FSInputFile(file_path))
  75.  
  76.     file_path.unlink(missing_ok=True)
  77.     await status.delete()
  78.  
  79.  
  80. @router.message(F.photo)
  81. async def image_handler(message: types.Message):
  82.     photo = await bot.get_file(message.photo[-1].file_id)
  83.     file_ext = photo.file_path.split(".")[-1]
  84.     file_path = Path(files_dir / f"image.{file_ext}")
  85.     await bot.download(message.photo[-1], file_path)
  86.  
  87.     corrupted_file_path = await corrupt_file(str(file_path))
  88.  
  89.     file_path.unlink(missing_ok=True)
  90.     Path(corrupted_file_path).rename(file_path)
  91.  
  92.     await message.reply_document(FSInputFile(file_path))
  93.  
  94.     file_path.unlink(missing_ok=True)
  95.  
  96.  
  97. @router.errors(F.update.message.as_("message"))
  98. async def errors_handler(error: ErrorEvent, message: types.Message):
  99.     logger.exception(f"An error occurred while handling request from {message.from_user.id}: {error.exception}")
  100.     await message.reply("❌Error happened. Please try again later.")
  101.  
  102.  
  103. async def main():
  104.     await bot.delete_webhook(drop_pending_updates=True)
  105.     dp.include_router(router)
  106.     await dp.start_polling(bot)
  107.  
  108. if __name__ == "__main__":
  109.     try:
  110.         asyncio.run(main())
  111.     except KeyboardInterrupt:
  112.         exit()
  113.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement