Advertisement
ElRandir42

Untitled

Nov 1st, 2019
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.23 KB | None | 0 0
  1. # coding=utf-8
  2.  
  3.  
  4. #-----Импортим Основные Модули----#
  5. from ez_modules.private_messages import main_private_messages
  6. from ez_modules.private_commands import main_private_commands
  7.  
  8. #-----Важное/Прочее-----#
  9. #from SQLight import SQLighter #Импортим класс с SQL
  10. import constants              #Импортим наши константы
  11. import secrets   #Для создания хэшей
  12. import random    #рандом
  13. import re        #Регулярки
  14. import time      #Время
  15. from time import sleep #Отдельно берём sleep для простоты вызова
  16. from apscheduler.schedulers.asyncio import AsyncIOScheduler #
  17. from apscheduler.triggers.combining import OrTrigger        # Отложки/Задачник
  18. from apscheduler.triggers.cron import CronTrigger           #
  19. import traceback #Ошибки
  20. from requests import exceptions #Ошибки тут/исключения
  21. import threading
  22. #import aiopika
  23. import logging
  24. import datetime
  25. import asyncio
  26. import asyncpg
  27. from asyncio import get_event_loop
  28.  
  29. #-----Импорты бота-----#
  30.  
  31. from aiogram import Bot, types, executor, dispatcher
  32. from aiogram.types import ParseMode
  33. from aiogram.dispatcher import Dispatcher
  34. from aiogram.contrib.fsm_storage.memory import MemoryStorage
  35. from aiogram.utils.exceptions import Throttled
  36. from aiogram.utils.executor import start_polling#, stop_polling
  37.  
  38. #-----Настройки бота-----#
  39. storage = MemoryStorage()
  40. loop = get_event_loop()
  41. #scheduler = AsyncIOScheduler(event_loop=loop)
  42.  
  43. bot = Bot(token=constants.TOKEN, loop=loop)
  44. errorbot = Bot(token=constants.ERRORTOKEN)
  45. dp = Dispatcher(bot, storage=storage)
  46. #------------------------#
  47.  
  48.  
  49.  
  50.  
  51. #loop.create_task(check_order(loop)) #Запускаем отложки.
  52.  
  53. logging.basicConfig(level=logging.INFO)
  54.  
  55. #------Ловим сообщения-----#
  56.  
  57. @dp.message_handler()
  58. async def all_message(message: types.Message):
  59.     try:
  60.         await main_private_messages(message)
  61.         await main_private_commands(message)
  62.         #await main_banner(message)
  63.         #await main_private(message)
  64.         #await main_inline(message)
  65.         #await cw3_module(message)
  66.     except Exception:
  67.         why = "Main core error."
  68.         await send_exception(message, why, traceback.format_exc())
  69.  
  70. #------Ловим Обратную Связь с Кнопотулек(CallBack)-----#
  71. #@dp.callback_query_handler()
  72. #async def all_callback(callback_query: types.CallbackQuery):
  73. #    try:
  74. #        await dp.throttle("callback_{0}".format(callback_query.from_user.id), rate=30)
  75. #    except Throttled:
  76. #        await bot.answer_callback_query(callback_query_id=callback_query.id, text="Эй! Не так быстро!", show_alert=False)
  77. #    else:
  78. #        try:
  79. #            await call_cw3_report(callback_query)
  80. #        except Exception:
  81. #            await bot.send_message(errorlogs, "chat_id = {0}\nuser_id = {1}\n{2}".format(callback_query.message.chat.id, callback_query.from_user.id, traceback.format_exc()))
  82.  
  83. #----Отправлялка ошибок----#
  84. async def send_exception(message, why, error):
  85.     try:
  86.         who_tg_id = message.from_user.id
  87.         who_tg_username = message.from_user.username if message.from_user.username else "None."
  88.         where_chat_id = message.chat.id
  89.         where_chat_title = message.chat.title if message.chat.title else "Private."
  90.         error_text = str(error)
  91.         when_tg_date = message.date
  92.         reason = why
  93.         result = f'Who:<a href="tg://user?id={who_tg_id}"> {who_tg_id} </a>| {when_tg_date}\nWhere: {where_chat_id} | [{where_chat_title}]\n'
  94.         result += f'Why: {reason}\n-----\n{error_text}'
  95.         await errorbot.send_message(constants.ERRORS, result, parse_mode=ParseMode.HTML, disable_web_page_preview=True)
  96.     except Exception:
  97.         print("Show must go on!\n", traceback.format_exc())
  98.  
  99.  
  100.  
  101. async def on_startup(dispatcher: dispatcher):
  102.     time_shit = str(time.strftime("%d.%m.%y %H:%M:%S", time.localtime()))
  103.     await bot.send_message(constants.ERRORS, "Сильви живее всех живыхъ. ~~~ {}".format(time_shit))
  104.     conn = await asyncpg.create_pool(user='юезрка', password='пароль', host='хост', port = '5432', database='database')
  105.     await conn.execute('INSERT INTO dich_plz(text_plz) VALUES($1)', 'Ура, у меня что-то да вышло. вроде')
  106.     print("Чекай бд, пёс")
  107.     dispatcher['db'] = conn
  108.  
  109. async def on_shutdown(dispatcher: dispatcher):
  110.     time_shit = str(time.strftime("%d.%m.%y %H:%M:%S", time.localtime()))
  111.     print("Сильви x_x  ~~~ {} \nСпаааатькииии.".format(time_shit))
  112.     #await bot.send_message(constants.ERRORS, "Сильви x_x  ~~~ {} \nСпаааатькииии.".format(time_shit))
  113.     #db = dp['db']
  114.     if 'db' in dispatcher:
  115.         await dispatcher['db'].close()
  116.  
  117. #------Ловим Инлайн(Inline)-----#
  118.  
  119.     #@dp.inline_handler()
  120.     #async def all_inline(inline_query: types.InlineQuery):
  121.     #await is_inline(inline_query)'''
  122.  
  123. #————————————Запуск—Поллинга—и—Задач—————————————————————————————————————————————————————————————————————————————————————————————————————————
  124. async def el():
  125.     time_shit = str(time.strftime("%d.%m.%y %H:%M:%S", time.localtime()))
  126.     try:
  127.         #await dispatcher.bot.send_message(chat_id=user.id, text="Bot started", disable_notification=True)
  128.         await errorbot.send_message(constants.ERRORS, "Сильви жива!. ~~~ {} \nПоллинг ожил.".format(time_shit))
  129.         #start_polling(dp)
  130.     except:
  131.         error = str(traceback.format_exc())
  132.         sleep(5)
  133.         print("{}\n\n{}\n\n".format(error, time_shit))
  134.         await errorbot.send_message(constants.ERRORS, "Сильви x_x  ~~~ {} \nПоллинг упал.".format(time_shit))
  135.         await el()
  136.  
  137.  
  138.  
  139. if __name__ == '__main__':
  140.     #asyncio.run(el())
  141.     #executor.start(dp, el())
  142.     start_polling(dp, on_startup=on_startup, on_shutdown=on_shutdown)
  143. '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement