def start(self): self.setUp() if not self._disable_persistence: logger.debug("Watching {} for runTime Options".format(self._file)) self._watcher = SyncWithFile(self._file) self._watcher.settings_modified = self.settings_modified self._task_runner.start()
def dump(self): if not self._disable_dump: self._watcher.stop_observer() tmpdict = self.dump_options() logger.debug("Dump Getting Called {}".format(tmpdict)) write_data_file(tmpdict, self._file) self._watcher.start_observer()
async def load_modules(): logger.info("Started loading modules...") for module in ALL_MODULES: modulename = module.split(".")[0] importlib.import_module(f"bot.modules.{modulename}") logger.debug("Module %s imported", module) logger.info("All modules loaded!")
async def add_note(event): reply_to_msg = await event.message.get_reply_message() logger.debug("Note text: %s", reply_to_msg.text) title = (await utils.get_command_args(event.message.raw_text))[0] await db.add_note_to_db(event.chat.id, title, reply_to_msg.text) await event.reply(f"Note {title} added!\n" "Use /shownote to check text")
def setup_runtime(uconfig): from bot.duel_links_runtime import DuelLinkRunTime from bot import logger from bot.providers import get_provider os.makedirs(uconfig.get('locations', 'log'), exist_ok=True) setup_logging() scheduler = BackgroundScheduler() dlRuntime = DuelLinkRunTime(uconfig, scheduler) dlRuntime.stop = False # Need to Ensure that it runs scheduler.start() try: dlRuntime.set_provider( get_provider(uconfig.get('bot', 'provider'))(scheduler, uconfig, dlRuntime)) except Exception as e: logger.critical( "Could not get a provider, take a look at your config file") logger.critical(e) logger.debug(traceback.format_exc()) sys.exit(1) try: dlRuntime.get_provider().sleep_factor = uconfig.getint( 'bot', 'sleep_factor') except Exception as e: logger.critical( "Could not set sleep factor, take a look at your config file") logger.critical(e) sys.exit(1) return dlRuntime
def dump(self): # TODO signal observer to turn off and then turn on again self._watcher.stop_observer() tmpdict = self.dump_options() logger.debug("Dump Getting Called {}".format(tmpdict)) write_data_file(tmpdict, self._file) self._watcher.start_observer()
def webhook(): update = Update.de_json(request.get_json(force=True), telebot) logger.debug("webhook update: {}".format(update)) utils.set_update(update) # bot_dispatcher.process_update(update) return "OK"
def getResponse(self, authorize=None): sys_params = { "method": self.get_api_name(), "app_key": self.key, "timestamp": str(int(time() * 1000)), "format": "json", "v": "2.0", "partner_id": self.partner_id, "sign_method": "md5", } if authorize is not None: sys_params['session'] = authorize params = self.get_api_params() sign_params = sys_params.copy() sign_params.update(params) sys_params['sign'] = self.sign(sign_params) headers = { 'Content-type': 'application/x-www-form-urlencoded;charset=UTF-8', "Cache-Control": "no-cache", "Connection": "Keep-Alive", } #headers = {"Content-Type":"application/x-www-form-urlencoded;charset=utf-8"} sys_params.update(params) logger.debug(json.dumps(sys_params)) r = requests.post(self.url, params=sys_params, headers=headers) r.raise_for_status() return r.json()
async def on_message(message: discord.Message): # Ignore any messages from myself just in case if message.author == client.user: return clean_message_content = utils.get_clean_message_content(message) # Skip any empty messages once cleaned if len(clean_message_content) == 0: return basic_match = utils.is_message_overwatch_time_basic(clean_message_content) ml_match = utils.is_message_overwatch_time_linear_regression( clean_message_content) if basic_match or ml_match: logger.debug(f'Reacting to message: {message.content}') await message.add_reaction(emoji='🅰️') await message.add_reaction(emoji='❗') if ml_match and not basic_match: await message.add_reaction(emoji='🤖') # Utilize message cool down if utils.is_spam(message): await message.add_reaction(emoji='⏳') else: await message.channel.send(get_reaction_gif())
def get_uin(msg): if msg['SystemInfo'] != 'uins': return if len(msg['Text']) == 0: return try: ins = itchat.instanceList[0] fullContact = ins.memberList # 更新用户数据到数据库 print('**** Wx_uin ****') if fullContact: for row in fullContact: print(row['Uin']) if row['Uin'] != 0: try: wxuser = Wxuser.query.filter_by( wx_uin=row['Uin']).first() if wxuser: wxuser.nickname = row['NickName'] wxuser.remarkname = row['RemarkName'] wxuser.wx_uid = row['UserName'] wxuser.save() else: wxuser = Wxuser(wx_uin=row['Uin'], nickname=row['NickName'], remarkname=row['RemarkName'], wx_uid=row['UserName']) wxuser.save() except: wxuser.rollback() except BaseException as e: logger.debug(e)
def handle_option_change(self, value): if self._provider is None: return if value == 'stop': if self.stop and self._provider.current_thread is not None: for x in threading.enumerate(): if x == self._provider.current_thread: logger.info("Stopping Bot Execution") elif self._provider.current_thread is not None: logger.info("Resuming Bot Execution") if value == 'run_now' and self.run_now: logger.info("Forcing run now") if self._provider.current_thread is None: try: self._scheduler.remove_job(self._job) except JobLookupError: pass self._scheduler.add_job(self._run_main, id='cron_main_force') else: logger.debug("Thread is currently running") self.run_now = False if value == 'next_run_at' and self._allow_event_change: try: self._scheduler.remove_job(self._job) except JobLookupError: pass self.schedule_next_run() next_run_at = self.next_run_at self._job = 'cron_main_at_{}'.format(next_run_at.isoformat()) self._scheduler.add_job(self._run_main, trigger='date', id=self._job, run_date=next_run_at)
def in_main(self): def thread_shutdown(_self): _self.shutdown() def handle_exception(_self, e): exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] logger.error(e) logger.debug("{} {} {}".format(exc_type, fname, exc_tb.tb_lineno)) logger.debug(traceback.format_exc()) logger.critical( "Provider does not have method correctly implemented cannot continue" ) tt = threading.Thread(target=thread_shutdown, args=(_self)) tt.start() # (schedule_shutdown, args=(), id='shutdown') self.active = True self.last_run_at = datetime.datetime.now() provider = self.get_provider() try: if not provider.is_process_running(): provider.start_process() provider.wait_for_ui(30) provider.pass_through_initial_screen(False) else: provider.pass_through_initial_screen(True) provider.compare_with_back_button() self.determine_playthrough(provider) except NotImplementedError as ee: handle_exception(self, ee) return except AttributeError as ee: handle_exception(self, ee) return except TypeError as ee: handle_exception(self, ee) return except Exception: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] logger.debug("{} {} {}".format(exc_type, fname, exc_tb.tb_lineno)) logger.debug(traceback.format_exc()) return if not self._disable_persistence: self._watcher.stop_observer() self._allow_event_change = False self.next_run_at = datetime.datetime.now() + datetime.timedelta( hours=4) next_run_at = self.next_run_at self._allow_event_change = True self._job = 'cron_main_at_{}'.format(next_run_at.isoformat()) self._scheduler.add_job(lambda: self._run_main, trigger='date', id=self._job, run_date=next_run_at) self.active = False self.stop = False if not self._disable_persistence: self._watcher.start_observer()
async def update_chat(event): logger.debug("Got chat action, updating info...") members = await utils.get_members(event.chat.id, only_ids=True) admins = await utils.get_admins(event.chat.id, only_ids=True) banned = await utils.get_banned(event.chat_id, only_ids=True) await db.update_chat(event.chat.id, {"$set": {"members": members, "admins": admins, "banned": banned}})
async def shown_note(event): title = (await utils.get_command_args(event.message.raw_text))[0] note = await db.get_note(event.chat.id, title) logger.debug("Got %s text: %s", title, note["text"]) if note: await event.reply(note["text"]) else: await event.reply(f"Note {title} not found!")
def tbd(bot, update, chat_data): user = update.message.from_user logger.debug("User %s Is asking fo a not developed function." % user.name) message = "Questo funzionalità è ancora in sviluppo!" update.message.reply_text(chat_id=update.message.chat_id, text=message, reply_markup=ReplyKeyboardRemove()) return CHOOSINGTREE
def __init__(self, config, scheduler): self._config = config self._file = config.get('bot', 'runTimePersistence') self._scheduler = scheduler self.setUp() logger.debug("Watching {} for runTime Options".format(self._file)) self._watcher = SyncWithFile(self._file) self._watcher.settings_modified = self.settings_modified
def unknown(bot, update): user = update.message.from_user logger.debug("User %s typed an unknown command : %s." % user.name, update.message.text) bot.send_message( chat_id=update.message.chat_id, text= "Perdona, ma non ho capito il comando.\n /help per avere maggiori info sui comandi disponibili", )
def Top_Up_right(id, updata_right): try: query = Wxuser.query.filter_by(id=id).first() query.right = int(updata_right) query.save() return '修改权限 成功' except BaseException as e: logger.debug('Send_msg_select:') logger.debug(e) return '没有查询到ID'
def Add_Message(msg): try: id = Wxuser().get_name(msg['FromUserName']) post = Wxpost(body=msg['Text'], timestamp=datetime.now(), wxuser_id=id, sender='普通') post.save() except BaseException as e: logger.debug('Add_Message:') logger.debug(e)
def timeout_dump(self): if self._timeout_dump is not None: try: self._timeout_dump.remove() except apscheduler.jobstores.base.JobLookupError: pass time = datetime.datetime.now() + datetime.timedelta(seconds=5) self._timeout_dump = self._scheduler.add_job(self.dump, trigger='date', run_date=time) logger.debug("Timeout dump Scheduled")
def Add_Sugges(msg, **kwargs): try: id = Wxuser().get_name(kwargs['FromUserName']) post = Wxpost(body=msg, timestamp=datetime.utcnow(), wxuser_id=id, sender='建议') post.save() except BaseException as e: logger.debug('Add_Sugges:') logger.debug(e)
def handle_exception(e): exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] logger.error(e) logger.debug("{} {} {}".format(exc_type, fname, exc_tb.tb_lineno)) logger.debug(traceback.format_exc()) logger.critical( "Provider does not have method correctly implemented cannot continue" ) tt = threading.Thread(target=thread_shutdown, args=()) tt.start() # (schedule_shutdown, args=(), id='shutdown')
def is_message_overwatch_time_linear_regression(cleaned_message_content: str) -> bool: """ Returns True/False if the message's content looks like it's for Overwatch using a linear regression model :param cleaned_message_content: The messages cleaned content (can be gotten from utils.get_clean_message_content) :return: bool: True/False if message's content looks like it's for Overwatch """ classifier: LogisticRegression = load(ml.model_path) vectorizer: CountVectorizer = load(ml.vectorizer_path) decision_result = classifier.decision_function(vectorizer.transform([cleaned_message_content]))[0] logger.debug(f'msg:{cleaned_message_content}, result:{decision_result}') # > 0 is considered a match, but let's try not to spam return decision_result > ml.decision_cutoff
def battle_calls(self, value): if not isinstance(value, dict): self.runtime_error_options("battle_calls", dict, type(value)) return if self._battle_calls == value: return self._battle_calls = value frame = inspect.currentframe() logger.debug("Value {} modified".format( inspect.getframeinfo(frame).function)) self.timeout_dump() self.handle_option_change('battle_calls')
def stop(self, stop): if not isinstance(stop, bool): self.runtime_error_options("stop", bool, type(stop)) return if self._stop == stop: return self._stop = stop frame = inspect.currentframe() logger.debug("Value {} modified".format( inspect.getframeinfo(frame).function)) self.timeout_dump() self.handle_option_change('stop')
def run_now(self, value): if not isinstance(value, bool): self.runtime_error_options("run_now", bool, type(value)) return if self._run_now == value: return self._run_now = value frame = inspect.currentframe() logger.debug("Value {} modified".format( inspect.getframeinfo(frame).function)) self.timeout_dump() self.handle_option_change('run_now')
def last_run_at(self, value): if not isinstance(value, datetime.datetime): self.runtime_error_options("last_run_at", datetime.datetime, type(value)) return if self._last_run_at == value: return self._last_run_at = value frame = inspect.currentframe() logger.debug("Value {} modified to {}".format( inspect.getframeinfo(frame).function, value)) self.timeout_dump()
def Com_Date_Poor(datemin, datemax, date_type='days'): ''' 计算时间差,用于循环 :param datemin: 开始时间 %m-%d-%Y :param datemax: 结束时间 :param date_type: 类型 :return: 返回数字差 ''' datemin = datetime.datetime.strptime(datemin, '%m-%d-%Y').date() datemax = datetime.datetime.strptime(datemax, '%m-%d-%Y').date() if date_type == 'days': ret = (datemax - datemin).days logger.debug(ret) return ret
def cancel(bot, update, chat_data): user = update.message.from_user logger.debug("User %s cancelled the conversation." % user.name) update.message.reply_text('Ciao, spero di rivederti presto!', reply_markup=ReplyKeyboardRemove()) for k in availableClassifierName: if k in chat_data: del chat_data[k] if 'choose' in chat_data: del chat_data['choose'] if 'conversationHistory' in chat_data: del chat_data['conversationHistory'] return ConversationHandler.END
def playmode(self, playmode): if not isinstance(playmode, str): self.runtime_error_options("playmode", str, type(playmode)) return if playmode not in self._available_modes: return if self._playmode == playmode: return self._playmode = playmode frame = inspect.currentframe() logger.debug("Value {} modified".format( inspect.getframeinfo(frame).function)) self.timeout_dump() self.handle_option_change('playmode')
def get_flows(): CHANNELS = gflow('channels.info', folder='team-info') USERS = gflow('users.info', folder='team-info') EMOJI = gflow('emoji.info', folder='team-info') logger.debug("Info loaded: channel = %r, users = %r, emoji = %r" % \ (bool(CHANNELS), bool(USERS), bool(EMOJI)))