def execute(): bot = EtherTokenMonitorBot(environ['TOKEN'], environ.get('STORAGE', 'storage'), environ['APIKEY'], request=Request(8, environ.get('PROXY', None)), mqueue=MessageQueue()) updater = Updater(bot=bot, use_context=True) class MyJackfruit(Jackfruit): def before_dispatch(self, update: 'Update', context: 'CallbackContext') -> None: bot.data_lock.acquire() def after_dispatch(self, update: 'Update', context: 'CallbackContext') -> None: bot.commit() bot.data_lock.release() MyJackfruit(updater.dispatcher, bot._main_menu, [('start', bot._main_menu.get_name())]).\ register(bot._add_wallet_enter_contract_address, bot._add_wallet_enter_token_address, bot._list_contracts, bot._list_tokens, ) updater.job_queue.run_repeating(bot.tick, 5 * 60) updater.start_polling() updater.idle()
def start_polling(updater: Updater, message_queue: MessageQueue) -> None: """ Starts the bot. :return: None """ try: updater.start_polling() except (Unauthorized, InvalidToken) as err: logging.error(err.message) logging.info("Check your API-Token in the config file") logging.info("Exiting...") raw_input() sys.exit(-1) except NetworkError: updater.start_polling() scheduler.start() updater.idle() scheduler.shutdown() message_queue.stop()
class MQBot(Bot): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._message_queue = MessageQueue(all_burst_limit=30, all_time_limit_ms=1000) def __del__(self): try: self._message_queue.stop() finally: super().__del__() def send_message(self, *args, **kwargs): is_group = kwargs.get('chat_id', 0) >= 0 return self._message_queue(Promise(super().send_message, args, kwargs), is_group) def send_photo(self, *args, **kwargs): is_group = kwargs.get('chat_id', 0) >= 0 return self._message_queue(Promise(super().send_photo, args, kwargs), is_group)
def main() -> None: """ Main method. Initializes all required variables and starts the bot. :return: None """ global config_handler, global_bot, schedule_util, db_handler, scheduler logging.info("Load Config...") try: config_handler = ConfigHandler() except ConfigValidationException as err: for message in err.message_list: logging.error(message) logging.info("Exiting... press Enter") raw_input() sys.exit(-1) except (ValueError, TypeError, KeyError) as err: logging.error(str(type(err).__name__) + ": " + str(err)) logging.info("Exiting...") raw_input() sys.exit(-1) logging.info("Init...") executors = {'default': ThreadPoolExecutor(200)} scheduler = BackgroundScheduler(executors=executors) message_queue: MessageQueue = MessageQueue(all_burst_limit=20, all_time_limit_ms=1000) try: global_bot = init_bot(message_queue) except InvalidToken as err: logging.error(err.message) logging.info("Check your API-Token in the config file") logging.info("Exiting...") raw_input() sys.exit(-1) updater: Updater = init_updater(global_bot) db_handler = DbHandler() schedule_util = ScheduleUtil(scheduler, config_handler.config, db_handler) init_handlers(updater.dispatcher) schedule_notifications() logging.info("Start...") start_polling(updater, message_queue)
def main(): logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) backend_name = CONFIG.get('General', 'backend') backend = importlib.import_module('backends.' + backend_name.lower()) client = backend.Client(CONFIG[backend_name]) init_polling(client) torrents_tracked = set() message_queue = MessageQueue() while True: for torrent in client.get_torrents(): if (torrent.id not in torrents_tracked and torrent.is_downloading()): torrents_tracked.add(torrent.id) threading.Thread(target=handle_torrent, args=(torrent, message_queue, torrents_tracked)).start() time.sleep(20)
def __init__(self, token, storage, api_key, *args, is_queued_def=True, mqueue=None, **kwargs): super().__init__(token, *args, **kwargs) self._is_messages_queued_default = is_queued_def self._msg_queue = mqueue or MessageQueue() self._storage = storage self._api_key = api_key self.data_lock = Lock() self.data = dict() """ { "user_id": { "contract": { "address": { amount } } } } """ with suppress(OSError, PickleError), open(self._storage, 'rb') as f: self.data = load(f) self._main_menu = MainMenu() self._add_wallet_enter_contract_address = AddWalletEnterContractAddress( ) self._add_wallet_enter_token_address = AddWalletEnterTokenAddress( self.data) self._list_contracts = ListContracts(self.data) self._list_tokens = ListTokens(self.data)
def __init__(self): token = "1699009884:AAHjE7wUGrSQgLUlIWgzucaV91dVJSDZhVs" message_queue = MessageQueue(all_burst_limit=29, all_time_limit_ms=1017) request = Request(con_pool_size=8) bot = MessageQueueBot(token, request=request, message_queue=message_queue) self._updater = Updater(bot=bot) self._dispatcher = self._updater.dispatcher self._db_manager = DbManager() self._localizer = Localizer(self._db_manager) self._health_checker = HealthChecker(self._updater.bot, self._db_manager) self._health_check_interval = int( os.environ.get('HEALTH_CHECK_INTERVAL')) self.__setup_command_handlers() self.__setup_callback_query_handlers() self.__setup_message_handlers() self.__setup_error_handler()
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._message_queue = MessageQueue(all_burst_limit=30, all_time_limit_ms=1000)
def __init__(self, *args, is_queued_def=True, mqueue=None, **kwargs): super(MQBot, self).__init__(*args, **kwargs) # below 2 attributes should be provided for decorator usage self._is_messages_queued_default = is_queued_def self._msg_queue = mqueue or MessageQueue()
class CoreQueueBot(Bot): def __new__(cls, *args, **kwargs): # Get default values from kwargs defaults = kwargs.get("defaults") # Make an instance of the class instance = super().__new__(cls) if not defaults: return instance # For each method ... for method_name, method in inspect.getmembers( instance, predicate=inspect.ismethod): # ... get kwargs argspec = inspect.getfullargspec(inspect.unwrap(method)) kwarg_names = argspec.args[-len(argspec.defaults or []):] # ... check if Defaults has a attribute that matches the kwarg name needs_default = [ kwarg_name for kwarg_name in kwarg_names if hasattr(defaults, kwarg_name) ] # ... make a dict of kwarg name and the default value default_kwargs = { kwarg_name: getattr(defaults, kwarg_name) for kwarg_name in needs_default if (getattr(defaults, kwarg_name) is not DEFAULT_NONE) } # ... apply the defaults using a partial if default_kwargs: setattr(instance, method_name, functools.partial(method, **default_kwargs)) return instance def __init__(self, *args, **kwargs): super(CoreQueueBot, self).__init__(*args, **kwargs) self._is_messages_queued_default = True self._msg_queue = MessageQueue() def stop(self): try: self._msg_queue.stop() except Exception: pass @queuedmessage def send_message(self, chat_id, text, parse_mode=None, disable_web_page_preview=None, disable_notification=False, reply_to_message_id=None, reply_markup=None, timeout=None, **kwargs): """Wrapped method would accept new `queued` and `isgroup` OPTIONAL arguments""" # self.add_defaults(kwargs) return super(CoreQueueBot, self).send_message(chat_id, text, parse_mode, disable_web_page_preview, disable_notification, reply_to_message_id, reply_markup, timeout, **kwargs)
def __init__(self, *args, **kwargs): super(CoreQueueBot, self).__init__(*args, **kwargs) self._is_messages_queued_default = True self._msg_queue = MessageQueue()