Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import asyncio
- import logging
- import sys
- import os
- import json
- import subprocess
- import signal
- import psutil
- import time
- import re
- import pandas as pd
- from datetime import datetime, timezone, timedelta
- from pathlib import Path
- from aiogram.types import Message
- from aiogram.enums import ParseMode
- from aiogram import Bot, Dispatcher, types
- from aiogram.filters import CommandObject
- from aiogram.filters.command import Command
- from io import BytesIO
- from aiogram.types import FSInputFile
- from aiogram import F
- from aiogram.exceptions import TelegramBadRequest
- from apscheduler.schedulers.asyncio import AsyncIOScheduler
- from db_fetcher import DBReader
- logging.basicConfig(level=logging.INFO)
- scheduler = AsyncIOScheduler()
- dbReader = DBReader('/mnt/app/database.ini')
- dbSideCashoutReader = DBReader('/mnt/app/side_tb_database.ini')
- bot = Bot(token="7030520224:AAEnyKFkIsgS6QzVnexn3EiWM9Dlgb3WBPY")
- dp = Dispatcher()
- def parse_clients_json():
- with open('clients.json', 'r') as clients_f:
- chat_ids = json.loads(''.join(clients_f.readlines()).replace(' ', '').replace('\n', ''))
- return chat_ids
- chat_ids = parse_clients_json()
- timezones = {
- -4788418340: timedelta(hours=9),
- # -1002150192437: timedelta(hours=3),
- }
- @dp.message(Command("liquidity_volume"))
- async def volume_balances(message: types.Message):
- chat_id = str(message.chat.id)
- print(chat_id)
- if chat_id not in chat_ids:
- await message.answer("Your chat is not in whitelist")
- return
- result = ''
- await dbReader.init_pool()
- tasks = [dbReader.get_volumes_by_group(group) for group in chat_ids[chat_id]]
- result = await asyncio.gather(*tasks, return_exceptions=True)
- await message.answer(''.join([res for res in result if res is not None and not isinstance(res, Exception)]))
- MAX_LENGTH = 4096
- @dp.message(Command("volume_balances"))
- async def volume_balances(message: types.Message):
- print(message.chat.id, file=sys.stderr)
- chat_id = str(message.chat.id)
- if chat_id not in chat_ids:
- await message.answer("Your chat is not in whitelist")
- return
- result = ''
- await dbReader.init_pool()
- tasks = [dbReader.get_balances_by_group(group, 'V') for group in chat_ids[chat_id]]
- result = await asyncio.gather(*tasks, return_exceptions=True)
- text = ''.join([res for res in result if res is not None and not isinstance(res, Exception)])
- for i in range(0, len(text), MAX_LENGTH):
- await message.answer(text[i:i+MAX_LENGTH])
- # balances_answer = ''
- # for name in sorted(balances.keys(), key=lambda s: s.lower()):
- # z = name.split('_')
- # parse_name = '/'.join(z[:2]) + ' ' + '_'.join(z[2:])
- # balances_answer += f'{parse_name}:{balances[name]}\n'
- # await message.answer(balances_answer)
- @dp.message(Command("mm_balances"))
- async def mm_balance(message: types.Message):
- chat_id = str(message.chat.id)
- if chat_id not in chat_ids:
- await message.answer("Your chat is not in whitelist")
- return
- result = ''
- await dbReader.init_pool()
- tasks = [dbReader.get_balances_by_group(group, 'M') for group in chat_ids[chat_id]]
- result = await asyncio.gather(*tasks, return_exceptions=True)
- text = ''.join([res for res in result if res is not None and not isinstance(res, Exception)])
- for i in range(0, len(text), MAX_LENGTH):
- await message.answer(text[i:i+MAX_LENGTH])
- @dp.message(Command("cashout_balances"))
- async def cashout_balances(message: types.Message):
- chat_id = str(message.chat.id)
- if chat_id not in chat_ids:
- await message.answer("Your chat is not in whitelist")
- return
- result = ''
- await dbReader.init_pool()
- await dbSideCashoutReader.init_pool(side=True)
- tasks_tb = [dbReader.get_balances_by_group(group, 'T') for group in chat_ids[chat_id] if '.' not in group]
- tasks_tb.extend([dbSideCashoutReader.get_balances_by_group(group) for group in chat_ids[chat_id] if '.' in group])
- result = await asyncio.gather(*tasks_tb, return_exceptions=True)
- await message.answer(''.join([res for res in result if res is not None and not isinstance(res, Exception)]))
- @dp.message(Command(re.compile(r"orderbook(_\w+)?")))
- async def orders(message: types.Message, command: CommandObject):
- chat_id = str(message.chat.id)
- if chat_id not in chat_ids:
- await message.answer("Your chat is not in whitelist")
- return
- exchange = None
- if command.args:
- exchange = command.args.strip().lower()
- else:
- match = re.match(r"/orderbook_(\w+)", message.text)
- if match:
- exchange = match.group(1).lower()
- if exchange == 'all':
- exchange = None
- await dbReader.init_pool()
- tasks = [dbReader.get_active_orders(group) for group in chat_ids[chat_id]]
- result = await asyncio.gather(*tasks, return_exceptions=True)
- result = [pd.DataFrame(res) for res in result if res is not None and not isinstance(res, Exception)]
- all_orders_df = pd.concat(result, ignore_index=True)
- if exchange is not None:
- all_orders_df = all_orders_df[all_orders_df['symbol'].str.contains(exchange, case=False, na=False)]
- all_orders_df = all_orders_df.reset_index(drop=True)
- output = BytesIO()
- with pd.ExcelWriter(output, engine='openpyxl') as writer:
- all_orders_df.to_excel(writer, index=True, sheet_name='ActualOrders')
- worksheet = writer.sheets['ActualOrders']
- for column_cells in worksheet.columns:
- length = max(len(str(cell.value)) for cell in column_cells)
- worksheet.column_dimensions[column_cells[0].column_letter].width = length + 2
- output.seek(0)
- await message.answer_document(
- types.BufferedInputFile(
- file=output.read(),
- filename=f"orderbook_{exchange if exchange else 'all'}.xlsx"
- ),
- caption=f"Excel file with actual orders{' for ' + exchange if exchange else ''}"
- )
- @dp.message(F.text.lower().contains('add_token_'))
- async def handler(message: Message):
- current_chat_id = str(message.chat.id)
- if '.' not in message.text:
- token_name = message.text.split('_')[2].upper()
- else:
- token_name = '_'.join(message.text.split('_')[2:])
- token_name = token_name.split('.')[0].upper() + '.' + token_name.split('.')[1].lower()
- if '<' in token_name and '>' in token_name:
- token_name = token_name[1:-1]
- if current_chat_id in chat_ids:
- if token_name in chat_ids[current_chat_id]:
- await message.reply(f"{token_name} have already been added")
- return
- chat_ids[current_chat_id].append(token_name)
- else:
- chat_ids[current_chat_id] = [token_name]
- with open('clients.json', 'w') as clients_f:
- clients_f.write(json.dumps(chat_ids))
- await dbReader.init_pool()
- await dbSideCashoutReader.init_pool(side=True)
- await dbReader.update_symbols_list()
- await dbSideCashoutReader.update_symbols_list(side=True)
- await message.reply(f"{token_name} was successfully added")
- @dp.message(F.text.lower().contains('delete_token_'))
- async def handler(message: Message):
- current_chat_id = str(message.chat.id)
- if '.' not in message.text:
- token_name = message.text.split('_')[2].upper()
- else:
- token_name = '_'.join(message.text.split('_')[2:])
- token_name = token_name.split('.')[0].upper() + '.' + token_name.split('.')[1].lower()
- if '<' in token_name and '>' in token_name:
- token_name = token_name[1:-1]
- if current_chat_id in chat_ids:
- if token_name not in chat_ids[current_chat_id]:
- await message.reply(f"{token_name} not in tokens list")
- return
- chat_ids[current_chat_id].remove(token_name)
- else:
- await message.reply(f"Your chat is not in chat ids")
- return
- with open('clients.json', 'w') as clients_f:
- clients_f.write(json.dumps(chat_ids))
- await dbReader.init_pool()
- await dbSideCashoutReader.init_pool(side=True)
- await dbReader.update_symbols_list()
- await dbSideCashoutReader.update_symbols_list(side=True)
- await message.reply(f"{token_name} was successfully deleted")
- @dp.message(F.text)
- async def bad_message(message: Message): # нельзя поднимать эту функцию выше!
- print(message.chat.id)
- # await message.answer("I don't understand you")
- async def main():
- await dp.start_polling(bot)
- await dbReader.close_connection()
- if __name__ == "__main__":
- asyncio.run(main())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement