forked from zovos/bot_tg
Compare commits
1 commit
a85ab1c639
...
a5b0691a4e
| Author | SHA1 | Date | |
|---|---|---|---|
| a5b0691a4e |
5 changed files with 75 additions and 105 deletions
BIN
__pycache__/main.cpython-313.pyc
Normal file
BIN
__pycache__/main.cpython-313.pyc
Normal file
Binary file not shown.
72
magnit_api.py
Normal file
72
magnit_api.py
Normal file
|
|
@ -0,0 +1,72 @@
|
||||||
|
from fastapi import FastAPI, Header, HTTPException
|
||||||
|
import requests
|
||||||
|
import time
|
||||||
|
|
||||||
|
app = FastAPI()
|
||||||
|
|
||||||
|
STORE_ID = 123456 # вставить storeId
|
||||||
|
API_TOKEN = "secret_token"
|
||||||
|
|
||||||
|
CACHE_TTL = 300 # 5 минут
|
||||||
|
cache = {
|
||||||
|
"data": None,
|
||||||
|
"timestamp": 0
|
||||||
|
}
|
||||||
|
|
||||||
|
SEARCH_PRODUCTS = [
|
||||||
|
"red bull",
|
||||||
|
"adrenaline rush",
|
||||||
|
"hoegaarden",
|
||||||
|
"baltika9",
|
||||||
|
]
|
||||||
|
|
||||||
|
@app.get("/magnit/products")
|
||||||
|
def get_products(x_token: str = Header(None)):
|
||||||
|
if x_token != API_TOKEN:
|
||||||
|
raise HTTPException(status_code=403, detail="Forbidden")
|
||||||
|
|
||||||
|
now = time.time()
|
||||||
|
|
||||||
|
# 🔹 кэш
|
||||||
|
if cache["data"] and now - cache["timestamp"] < CACHE_TTL:
|
||||||
|
return cache["data"]
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
"User-Agent": "Mozilla/5.0",
|
||||||
|
"Accept": "application/json",
|
||||||
|
}
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
for query in SEARCH_PRODUCTS:
|
||||||
|
params = {
|
||||||
|
"query": query,
|
||||||
|
"storeId": STORE_ID,
|
||||||
|
"limit": 5
|
||||||
|
}
|
||||||
|
|
||||||
|
resp = requests.get(
|
||||||
|
"https://web-gateway.middle-api.magnit.ru/api/products/search",
|
||||||
|
headers=headers,
|
||||||
|
params=params,
|
||||||
|
timeout=10
|
||||||
|
)
|
||||||
|
|
||||||
|
if resp.status_code != 200:
|
||||||
|
continue
|
||||||
|
|
||||||
|
data = resp.json().get("data", [])
|
||||||
|
|
||||||
|
for item in data:
|
||||||
|
name = item.get("name", "")
|
||||||
|
price = item.get("price")
|
||||||
|
if price:
|
||||||
|
results.append({
|
||||||
|
"name": name,
|
||||||
|
"price": price
|
||||||
|
})
|
||||||
|
|
||||||
|
cache["data"] = results
|
||||||
|
cache["timestamp"] = now
|
||||||
|
|
||||||
|
return results
|
||||||
107
main.py
107
main.py
|
|
@ -2,16 +2,15 @@ import asyncio
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import requests
|
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from textwrap import wrap
|
from textwrap import wrap
|
||||||
import random
|
import random
|
||||||
|
|
||||||
from aiogram import Bot, Dispatcher, F, types
|
from aiogram import Bot, Dispatcher, F
|
||||||
from aiogram.enums import ParseMode
|
from aiogram.enums import ParseMode
|
||||||
from aiogram.filters import Command, CommandStart
|
from aiogram.filters import Command, CommandStart
|
||||||
from aiogram.types import BufferedInputFile, Message, BotCommand, FSInputFile
|
from aiogram.types import BufferedInputFile, Message, BotCommand
|
||||||
from aiogram.client.default import DefaultBotProperties
|
from aiogram.client.default import DefaultBotProperties
|
||||||
from PIL import Image, ImageDraw, ImageFont
|
from PIL import Image, ImageDraw, ImageFont
|
||||||
from datetime import datetime, time, timedelta
|
from datetime import datetime, time, timedelta
|
||||||
|
|
@ -132,8 +131,6 @@ HINT_TEXT = (
|
||||||
f"• /maket «id» «текст» — доступные: {templates_list_text()} (1: 737x414, точка 104,240).\n"
|
f"• /maket «id» «текст» — доступные: {templates_list_text()} (1: 737x414, точка 104,240).\n"
|
||||||
"• /gen_mem Up:верх Down:низ — отправь с фото (как подпись) или ответом на фото.\n"
|
"• /gen_mem Up:верх Down:низ — отправь с фото (как подпись) или ответом на фото.\n"
|
||||||
"• /break — узнать, сколько минут до перекура.\n"
|
"• /break — узнать, сколько минут до перекура.\n"
|
||||||
"• /prices — старый способ цен.\n"
|
|
||||||
"• /fetch — свежие цены с x-server.\n"
|
|
||||||
"Подсказка: в группах команда должна быть слитно с ботом (/gen_mem@username)."
|
"Подсказка: в группах команда должна быть слитно с ботом (/gen_mem@username)."
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -385,99 +382,9 @@ async def handle_size(message: Message):
|
||||||
|
|
||||||
await message.answer(
|
await message.answer(
|
||||||
f"📏 Твой хуек: {size} см\n"
|
f"📏 Твой хуек: {size} см\n"
|
||||||
f"Ты: {status}"
|
f"Ты {status}"
|
||||||
)
|
)
|
||||||
|
|
||||||
KEYWORDS = {'крип', 'радиохэд', 'creep', 'radiohead'}
|
|
||||||
# I'M CREEP
|
|
||||||
async def handle_keywords(message: types.Message):
|
|
||||||
|
|
||||||
if message.text and message.text.startswith('/'):
|
|
||||||
return
|
|
||||||
|
|
||||||
text = message.text.lower()
|
|
||||||
|
|
||||||
if any(re.search(rf'\b{word}\b', text) for word in KEYWORDS):
|
|
||||||
audio_path = BASE_DIR / "maket" / "Radiohead - Creep.mp3"
|
|
||||||
|
|
||||||
if audio_path.exists():
|
|
||||||
await message.answer_audio(
|
|
||||||
audio=FSInputFile(audio_path),
|
|
||||||
caption="I'm a creep, I'm a weirdo..."
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
logger.warning(f"Файл не найден по пути: {audio_path}")
|
|
||||||
|
|
||||||
async def handle_prices(message: Message):
|
|
||||||
def fetch():
|
|
||||||
return requests.get(
|
|
||||||
"https://bebrik.xyz/magnit/products",
|
|
||||||
headers={"X-Token": "sisi"},
|
|
||||||
timeout=10,
|
|
||||||
)
|
|
||||||
|
|
||||||
try:
|
|
||||||
resp = await asyncio.to_thread(fetch)
|
|
||||||
|
|
||||||
if resp.status_code != 200:
|
|
||||||
await message.answer("пошел нахуй")
|
|
||||||
return
|
|
||||||
|
|
||||||
data = resp.json()
|
|
||||||
|
|
||||||
if not data:
|
|
||||||
await message.answer("иди нахуй")
|
|
||||||
return
|
|
||||||
|
|
||||||
text = "смерть в 25:\n\n"
|
|
||||||
for item in data:
|
|
||||||
name = item.get("name")
|
|
||||||
price = item.get("price")
|
|
||||||
text += f"{name} — {price} ₽\n"
|
|
||||||
|
|
||||||
await message.answer(text[:4000])
|
|
||||||
|
|
||||||
except Exception:
|
|
||||||
await message.answer("unable to connect x-server гандон")
|
|
||||||
|
|
||||||
|
|
||||||
async def handle_fetch(message: Message):
|
|
||||||
def fetch():
|
|
||||||
return requests.get(
|
|
||||||
"https://mirror.porno4free.ru/magnit/magnit/prices/all",
|
|
||||||
headers={"x-token": "secret_token"},
|
|
||||||
timeout=10,
|
|
||||||
)
|
|
||||||
|
|
||||||
try:
|
|
||||||
resp = await asyncio.to_thread(fetch)
|
|
||||||
if resp.status_code != 200:
|
|
||||||
await message.reply("пошел нахуй")
|
|
||||||
return
|
|
||||||
|
|
||||||
data = resp.json()
|
|
||||||
if not isinstance(data, dict) or not data:
|
|
||||||
await message.reply("иди нахуй")
|
|
||||||
return
|
|
||||||
|
|
||||||
lines = ["смерть в 25:"]
|
|
||||||
# сортируем категории для стабильного вывода
|
|
||||||
for group in sorted(data.keys()):
|
|
||||||
items = data.get(group)
|
|
||||||
lines.append(f"\n{group}:")
|
|
||||||
if not isinstance(items, list):
|
|
||||||
continue
|
|
||||||
for item in items:
|
|
||||||
name = item.get("name")
|
|
||||||
price = item.get("price")
|
|
||||||
if not name or price is None:
|
|
||||||
continue
|
|
||||||
lines.append(f"{name} — {price} ₽")
|
|
||||||
text = "\n".join(lines)
|
|
||||||
await message.answer(text[:4000])
|
|
||||||
except Exception:
|
|
||||||
await message.answer("unable to connect x-server гандон")
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
token = os.getenv("BOT_TOKEN")
|
token = os.getenv("BOT_TOKEN")
|
||||||
|
|
@ -497,8 +404,6 @@ def main():
|
||||||
BotCommand(command="gen_mem", description="Мем из фото (ответом)"),
|
BotCommand(command="gen_mem", description="Мем из фото (ответом)"),
|
||||||
BotCommand(command="break", description="Сколько минут до перекура"),
|
BotCommand(command="break", description="Сколько минут до перекура"),
|
||||||
BotCommand(command="size", description="хуй"),
|
BotCommand(command="size", description="хуй"),
|
||||||
BotCommand(command="prices", description="цены x-server"),
|
|
||||||
BotCommand(command="fetch", description="цены (новый источник)"),
|
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
except Exception: # noqa: WPS440
|
except Exception: # noqa: WPS440
|
||||||
|
|
@ -511,17 +416,11 @@ def main():
|
||||||
dp.message.register(handle_break, Command("break"))
|
dp.message.register(handle_break, Command("break"))
|
||||||
dp.message.register(handle_maket, Command("maket"))
|
dp.message.register(handle_maket, Command("maket"))
|
||||||
dp.message.register(handle_size, Command("size"))
|
dp.message.register(handle_size, Command("size"))
|
||||||
dp.message.register(handle_prices, Command("prices"))
|
|
||||||
dp.message.register(handle_fetch, Command("fetch"))
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
async def handle_gen_mem_cmd(message: Message, bot: Bot):
|
async def handle_gen_mem_cmd(message: Message, bot: Bot):
|
||||||
await handle_gen_mem(message, bot)
|
await handle_gen_mem(message, bot)
|
||||||
|
|
||||||
dp.message.register(handle_gen_mem_cmd, Command("gen_mem"))
|
dp.message.register(handle_gen_mem_cmd, Command("gen_mem"))
|
||||||
|
|
||||||
dp.message.register(handle_keywords, F.text)
|
|
||||||
|
|
||||||
logger.info("Bot is starting...")
|
logger.info("Bot is starting...")
|
||||||
asyncio.run(dp.start_polling(bot, allowed_updates=dp.resolve_used_update_types()))
|
asyncio.run(dp.start_polling(bot, allowed_updates=dp.resolve_used_update_types()))
|
||||||
|
|
|
||||||
Binary file not shown.
|
|
@ -1,3 +1,2 @@
|
||||||
aiogram==3.4.1
|
aiogram==3.4.1
|
||||||
pillow==10.3.0
|
pillow==10.3.0
|
||||||
requests==2.31.0
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue