Advertisement
den4ik2003

Untitled

Jul 4th, 2025
11
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.68 KB | None | 0 0
  1. import asyncio
  2. import logging
  3. import sys
  4. import os
  5. import json
  6. import subprocess
  7. import signal
  8. import psutil
  9. import time
  10. import re
  11. import pandas as pd
  12. from datetime import datetime, timezone, timedelta
  13. from pathlib import Path
  14. from aiogram.types import Message
  15. from aiogram.enums import ParseMode
  16. from aiogram import Bot, Dispatcher, types
  17. from aiogram.filters import CommandObject
  18. from aiogram.filters.command import Command
  19. from io import BytesIO
  20. from aiogram.types import FSInputFile
  21. from aiogram import F
  22. from aiogram.exceptions import TelegramBadRequest
  23. from apscheduler.schedulers.asyncio import AsyncIOScheduler
  24. from db_fetcher import DBReader
  25.  
  26. logging.basicConfig(level=logging.INFO)
  27.  
  28. scheduler = AsyncIOScheduler()
  29. dbReader = DBReader('/mnt/app/database.ini')
  30. dbSideCashoutReader = DBReader('/mnt/app/side_tb_database.ini')
  31. bot = Bot(token="7030520224:AAEnyKFkIsgS6QzVnexn3EiWM9Dlgb3WBPY")
  32. dp = Dispatcher()
  33.  
  34. def parse_clients_json():
  35. with open('clients.json', 'r') as clients_f:
  36. chat_ids = json.loads(''.join(clients_f.readlines()).replace(' ', '').replace('\n', ''))
  37. return chat_ids
  38.  
  39. chat_ids = parse_clients_json()
  40.  
  41. timezones = {
  42. -4788418340: timedelta(hours=9),
  43. # -1002150192437: timedelta(hours=3),
  44. }
  45.  
  46. @dp.message(Command("liquidity_volume"))
  47. async def volume_balances(message: types.Message):
  48. chat_id = str(message.chat.id)
  49. print(chat_id)
  50. if chat_id not in chat_ids:
  51. await message.answer("Your chat is not in whitelist")
  52. return
  53.  
  54. result = ''
  55. await dbReader.init_pool()
  56. tasks = [dbReader.get_volumes_by_group(group) for group in chat_ids[chat_id]]
  57. result = await asyncio.gather(*tasks, return_exceptions=True)
  58. await message.answer(''.join([res for res in result if res is not None and not isinstance(res, Exception)]))
  59.  
  60.  
  61. MAX_LENGTH = 4096
  62.  
  63. @dp.message(Command("volume_balances"))
  64. async def volume_balances(message: types.Message):
  65. print(message.chat.id, file=sys.stderr)
  66.  
  67. chat_id = str(message.chat.id)
  68. if chat_id not in chat_ids:
  69. await message.answer("Your chat is not in whitelist")
  70. return
  71.  
  72. result = ''
  73. await dbReader.init_pool()
  74. tasks = [dbReader.get_balances_by_group(group, 'V') for group in chat_ids[chat_id]]
  75. result = await asyncio.gather(*tasks, return_exceptions=True)
  76. text = ''.join([res for res in result if res is not None and not isinstance(res, Exception)])
  77. for i in range(0, len(text), MAX_LENGTH):
  78. await message.answer(text[i:i+MAX_LENGTH])
  79.  
  80. # balances_answer = ''
  81. # for name in sorted(balances.keys(), key=lambda s: s.lower()):
  82. # z = name.split('_')
  83. # parse_name = '/'.join(z[:2]) + ' ' + '_'.join(z[2:])
  84. # balances_answer += f'{parse_name}:{balances[name]}\n'
  85. # await message.answer(balances_answer)
  86.  
  87.  
  88. @dp.message(Command("mm_balances"))
  89. async def mm_balance(message: types.Message):
  90. chat_id = str(message.chat.id)
  91. if chat_id not in chat_ids:
  92. await message.answer("Your chat is not in whitelist")
  93. return
  94.  
  95. result = ''
  96. await dbReader.init_pool()
  97. tasks = [dbReader.get_balances_by_group(group, 'M') for group in chat_ids[chat_id]]
  98. result = await asyncio.gather(*tasks, return_exceptions=True)
  99. text = ''.join([res for res in result if res is not None and not isinstance(res, Exception)])
  100. for i in range(0, len(text), MAX_LENGTH):
  101. await message.answer(text[i:i+MAX_LENGTH])
  102.  
  103.  
  104. @dp.message(Command("cashout_balances"))
  105. async def cashout_balances(message: types.Message):
  106. chat_id = str(message.chat.id)
  107. if chat_id not in chat_ids:
  108. await message.answer("Your chat is not in whitelist")
  109. return
  110.  
  111. result = ''
  112. await dbReader.init_pool()
  113. await dbSideCashoutReader.init_pool(side=True)
  114. tasks_tb = [dbReader.get_balances_by_group(group, 'T') for group in chat_ids[chat_id] if '.' not in group]
  115. tasks_tb.extend([dbSideCashoutReader.get_balances_by_group(group) for group in chat_ids[chat_id] if '.' in group])
  116.  
  117. result = await asyncio.gather(*tasks_tb, return_exceptions=True)
  118. await message.answer(''.join([res for res in result if res is not None and not isinstance(res, Exception)]))
  119.  
  120.  
  121. @dp.message(Command(re.compile(r"orderbook(_\w+)?")))
  122. async def orders(message: types.Message, command: CommandObject):
  123. chat_id = str(message.chat.id)
  124. if chat_id not in chat_ids:
  125. await message.answer("Your chat is not in whitelist")
  126. return
  127.  
  128. exchange = None
  129. if command.args:
  130. exchange = command.args.strip().lower()
  131. else:
  132. match = re.match(r"/orderbook_(\w+)", message.text)
  133. if match:
  134. exchange = match.group(1).lower()
  135. if exchange == 'all':
  136. exchange = None
  137.  
  138. await dbReader.init_pool()
  139. tasks = [dbReader.get_active_orders(group) for group in chat_ids[chat_id]]
  140. result = await asyncio.gather(*tasks, return_exceptions=True)
  141. result = [pd.DataFrame(res) for res in result if res is not None and not isinstance(res, Exception)]
  142.  
  143. all_orders_df = pd.concat(result, ignore_index=True)
  144. if exchange is not None:
  145. all_orders_df = all_orders_df[all_orders_df['symbol'].str.contains(exchange, case=False, na=False)]
  146. all_orders_df = all_orders_df.reset_index(drop=True)
  147.  
  148. output = BytesIO()
  149. with pd.ExcelWriter(output, engine='openpyxl') as writer:
  150. all_orders_df.to_excel(writer, index=True, sheet_name='ActualOrders')
  151.  
  152. worksheet = writer.sheets['ActualOrders']
  153. for column_cells in worksheet.columns:
  154. length = max(len(str(cell.value)) for cell in column_cells)
  155. worksheet.column_dimensions[column_cells[0].column_letter].width = length + 2
  156.  
  157. output.seek(0)
  158.  
  159. await message.answer_document(
  160. types.BufferedInputFile(
  161. file=output.read(),
  162. filename=f"orderbook_{exchange if exchange else 'all'}.xlsx"
  163. ),
  164. caption=f"Excel file with actual orders{' for ' + exchange if exchange else ''}"
  165. )
  166.  
  167.  
  168. @dp.message(F.text.lower().contains('add_token_'))
  169. async def handler(message: Message):
  170. current_chat_id = str(message.chat.id)
  171. if '.' not in message.text:
  172. token_name = message.text.split('_')[2].upper()
  173. else:
  174. token_name = '_'.join(message.text.split('_')[2:])
  175. token_name = token_name.split('.')[0].upper() + '.' + token_name.split('.')[1].lower()
  176.  
  177. if '<' in token_name and '>' in token_name:
  178. token_name = token_name[1:-1]
  179.  
  180. if current_chat_id in chat_ids:
  181. if token_name in chat_ids[current_chat_id]:
  182. await message.reply(f"{token_name} have already been added")
  183. return
  184. chat_ids[current_chat_id].append(token_name)
  185. else:
  186. chat_ids[current_chat_id] = [token_name]
  187.  
  188. with open('clients.json', 'w') as clients_f:
  189. clients_f.write(json.dumps(chat_ids))
  190.  
  191. await dbReader.init_pool()
  192. await dbSideCashoutReader.init_pool(side=True)
  193.  
  194. await dbReader.update_symbols_list()
  195. await dbSideCashoutReader.update_symbols_list(side=True)
  196.  
  197. await message.reply(f"{token_name} was successfully added")
  198.  
  199.  
  200. @dp.message(F.text.lower().contains('delete_token_'))
  201. async def handler(message: Message):
  202. current_chat_id = str(message.chat.id)
  203. if '.' not in message.text:
  204. token_name = message.text.split('_')[2].upper()
  205. else:
  206. token_name = '_'.join(message.text.split('_')[2:])
  207. token_name = token_name.split('.')[0].upper() + '.' + token_name.split('.')[1].lower()
  208.  
  209. if '<' in token_name and '>' in token_name:
  210. token_name = token_name[1:-1]
  211.  
  212. if current_chat_id in chat_ids:
  213. if token_name not in chat_ids[current_chat_id]:
  214. await message.reply(f"{token_name} not in tokens list")
  215. return
  216. chat_ids[current_chat_id].remove(token_name)
  217. else:
  218. await message.reply(f"Your chat is not in chat ids")
  219. return
  220.  
  221. with open('clients.json', 'w') as clients_f:
  222. clients_f.write(json.dumps(chat_ids))
  223.  
  224. await dbReader.init_pool()
  225. await dbSideCashoutReader.init_pool(side=True)
  226.  
  227. await dbReader.update_symbols_list()
  228. await dbSideCashoutReader.update_symbols_list(side=True)
  229.  
  230. await message.reply(f"{token_name} was successfully deleted")
  231.  
  232.  
  233. @dp.message(F.text)
  234. async def bad_message(message: Message): # нельзя поднимать эту функцию выше!
  235. print(message.chat.id)
  236. # await message.answer("I don't understand you")
  237.  
  238.  
  239. async def main():
  240. await dp.start_polling(bot)
  241. await dbReader.close_connection()
  242.  
  243. if __name__ == "__main__":
  244. asyncio.run(main())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement