dxy_ya_bot/bot.py
2024-10-30 23:48:18 +03:00

51 lines
2.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import logging, requests, json
from telegram import Update, ReplyKeyboardMarkup
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, MessageHandler, filters
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
logger = logging.getLogger(__name__)
bot_token = '7636065770:AAF8UV5Vb2F7aRuO8EYTyv0xGBmd3dQeonQ'
ya_token = 'y0_AgAAAABiFlEmAAbJ0QAAAAEWkS6NAABACUMU8JdJWoZeypr0qWs05ayGjQ'
ya_url = 'https://partner2.yandex.ru/api/statistics2/get.json'
msg_to_period = {
"Сегодня": "today",
"Вчера": "yesterday",
"Месяц": "30days"
}
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
reply_keyboard = [[ "Сегодня", "Вчера", "Месяц" ]]
await update.message.reply_text("Какую стату вывести", reply_markup=ReplyKeyboardMarkup(reply_keyboard))
async def ya_api(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
reply = await fetch_data(update.message.text)
await update.message.reply_text(reply)
async def fetch_data(msg_period: str) -> str:
response = requests.get(ya_url, headers={'Authorization': ya_token}, params={
'lang': 'ru',
'period': msg_to_period[msg_period],
'field': ['shows', 'hits_render', 'partner_wo_nds', 'cpmv_partner_wo_nds']
})
json_data = json.loads(response.text)
logger.info(json_data)
data = json_data['data']['totals']['2'][0]
return f"Данные за {msg_period}\n\n\
Подборы рекламы: {data['hits_render']}\n\
Видимые показы: {data['shows']}\n\
Вознаграждение партнеру за рекламу: {data['partner_wo_nds']} руб.\n\
Стоимость 1к видимых показов: {data['cpmv_partner_wo_nds']} руб."
if __name__ == '__main__':
application = ApplicationBuilder().token(bot_token).build()
application.add_handler(CommandHandler('start', start))
application.add_handler(MessageHandler(filters.Regex("^(Сегодня|Вчера|Месяц)$"), ya_api))
application.run_polling()