def main(): Log.info('Strat initializing....') Log.info('Debug enable: {}', Log.get_debug_info()[0]) Log.debug(1, 'Debug level: {}', Log.get_debug_info()[1]) bot_class() Log.info('Bot is now running!') while True: time.sleep(30)
def run(self): time.sleep(self.time_delay) try: bot_class.bot_self.deleteMessage(self.target) except telepot.exception.TelegramError as e: if e[1] == 400: # Catch access denied return Log.warn('Catched telepot.exception.TelegramError:{}', repr(e))
def sql_clear_comment(sql_file_path): with open(sql_file_path) as fin: r = fin.readlines() with open(sql_file_path,'w') as fout: for x in r: if x[:2] != '--': #content.append(x) fout.write(x) Log.debug(5, '[x = {}]',x[:-1])
def requestThread(): LATEST = None while True: try: LATEST = mainRequest(LATEST) except: Log.write_traceback_error('Error while requesting file') finally: time.sleep(Config.backup.interval)
def onMessage(self, msg): try: content_type, chat_type, chat_id = self.glance(msg) if content_type == 'new_chat_member' and not self.aftermemberpool.check( msg['new_chat_participant']['id']): self.aftermemberpool.write(msg['new_chat_participant']['id'], 'null') elif content_type == 'text' and chat_type == 'private': msgStr = msg['text'] if chat_id == int(Config.bot.owner): if msgStr[:5] == '/send': self.sendMessage(Config.bot.group_id, msgStr[6:], parse_mode='Markdown') elif msgStr == '/len': self.sendMessage( chat_id, 'Current people length: {}'.format( len(self.memberpool.members))) elif msgStr[:4] == '/del': self.aftermemberpool.write(int(msgStr[5:]), 'null') self.memberpool.delete(int(msgStr[5:])) self.sendMessage(chat_id, '`{}` deleted!'.format(msgStr[5:]), parse_mode='Markdown') elif msgStr == '/list': s = '' for k, v in self.memberpool.members.items(): s += '`{}`: {}\n'.format(k, b64decode(v)) self.sendMessage(chat_id, s, parse_mode='Markdown') del s elif self.bot.getChatMember(int(Config.bot.group_id), chat_id)['status'] != 'member': return elif msgStr == '/flag 233': if not self.memberpool.check(msg['from']['id']) and \ not self.aftermemberpool.check(msg['from']['id']): self.memberpool.write(msg['from']['id'], parse_name(msg['from'])) self.sendMessage( chat_id, 'Register successful, your *user_id* is `{}`'. format(chat_id), parse_mode='Markdown') elif msgStr == '/ping': if self.memberpool.check(msg['from']['id']): self.sendMessage(chat_id, 'You already registed') else: self.sendMessage( chat_id, 'Unregistered, please send me /flag with flag to register' ) except Exception: Log.warn('Raised exception: \n{}', traceback.format_exc())
def custom_init(self, *args, **kwargs): self.syncLock = Lock() self.cache = DiskCache('data/id_cache', default_return_type=dict()) self.external_store = self.cache.read_without_except() with self.syncLock: t = Thread(target=self.__specfunc) t.daemon = True t.start() Log.info('Initializing other cache') self.gcache = group_cache_class(init=self) self.gcache.load() self.pcache = poem_class() self.fail_with_md = 'Markdown configure error, check settings or contact bot administrator if you think you are right'
def sendMessage(self, chat_id, message, **kwargs): return_value = None while True: try: Log.debug( 2, 'Calling telepot_bot.sendMessage() [chat_id = {},message = {}, kwargs = {}]', chat_id, repr(message), kwargs) return_value = self.bot.sendMessage(chat_id, message, **kwargs) break except telepot.exception.TelegramError as e: # Markdown fail if self.fail_with_md is not None and e[-1]['error_code'] == 400 and \ 'Can\'t find end of the entity starting at byte' in e[-1]['description']: # Must fail safe return_value = self.bot.sendMessage( chat_id, 'Error: {}\nRaw description: {}'.format( self.fail_with_md, e[-1]['description'])) break else: Log.error('Raise exception: {}', repr(e)) raise e except Exception as e: Log.error('Exception {} occurred', e.__name__) Log.debug( 1, 'on telepot_bot.sendMessage() [chat_id = {},message = {}, kwargs = {}]', chat_id, repr(message), kwargs) time.sleep(self.WAIT_TIME) return return_value
def start(self, times): Log.info('Start random process') for time in xrange(0, times): Log.info('Current group:{}', repr(self.l)) r = random.randint(50000, 99999) Log.info('Randomize list {} times', r) for x in xrange(0, r): self.rand_list() Log.info('Randomize done. Current group:{}', repr(self.l)) result = self.l.pop(random.randint(0, len(self.l) - 1)) self.winner.append(result) Log.info('Round {} Winner is : {} (id:{})', time + 1, b64decode(self.member.pop(result)), result) self.cleanup()
def get_from_telegram_server(): offset = None # running offset allowed_upd = allowed_updates while 1: try: result = self.getUpdates(offset=offset, timeout=timeout, allowed_updates=allowed_upd) allowed_upd = None if len(result) > 0: offset = max( [relay_to_collector(update) for update in result]) + 1 except telepot.exception.BadHTTPResponse as e: Log.write_traceback_error( 'Catched telepot.exception.BadHTTPResponse') if e.status == 502: time.sleep(30) except urllib3.exceptions.ReadTimeoutError: Log.write_traceback_error( 'Catched requests.exceptions.ReadTimeoutError') except telepot.exception.TelegramError as e: Log.write_traceback_error( 'Catched telepot.exception.TelegramError (code = %d)' % e[1]) except urllib3.exceptions.ProtocolError: Log.write_traceback_error( 'Catched urllib3.exceptions.ProtocolError') except: traceback.print_exc() finally: time.sleep(relax)
def backupThread(): Log.info('Starting backup function') while True: now_time = time.strftime('%Y%m%d_%H%M%S') os.system("tar czfP {}/{}.tar.gz {}/world".format( Config.backup.webroot, now_time, Config.backup.mc_path)) try: with open('{}/LATEST2'.format(Config.backup.webroot), 'w') as fout, open('{}/LATEST'.format( Config.backup.webroot)) as fin: fout.write(fin.read()) except IOError: pass with open('{}/LATEST'.format(Config.backup.webroot), 'w') as fout: fout.write(now_time) Log.info('{}.tar.gz backuped.', now_time) fileChecking(Config.backup.webroot) time.sleep(Config.backup.interval)
def split_list(l, split_count, Fill_with_None=False): assert isinstance(l, list) or l is None Count = len(l)//split_count Log.debug(3, 'Count:{}', Count) if Count == 0: tmp = [[x] for x in l] if Fill_with_None: for x in xrange(len(tmp), split_count): tmp.append(None) return tmp if len(l)%split_count: Count += 1 tmp = [l[Count*x:Count*(x+1)] for x in xrange(0, split_count)] for x in tmp: if x == []: tmp.remove(x) if Fill_with_None: for x in xrange(len(tmp), split_count): tmp.append(None) return tmp
def mainRequest(LATEST): r = requests.get('{}/LATEST'.format(Config.backup.website), timeout=10) if LATEST == r.text: return LATEST _LATEST = LATEST LATEST = r.text s = requests.get('{}/{}.tar.gz'.format(Config.backup.website, LATEST), stream=True, timeout=10) try: s.raise_for_status() except Exception as e: Log.error('Catched Exception:`{}\'', repr(e)) return _LATEST # From: https://stackoverflow.com/questions/16694907/how-to-download-large-file-in-python-with-requests-py with open("{}/{}.tar.gz".format(Config.backup.download_path, LATEST), 'wb') as fout: for chunk in s.iter_content(chunk_size=1024): if not chunk: break fout.write(chunk) Log.info('{}.tar.gz downloaded.', LATEST) fileChecking(Config.backup.download_path) return LATEST
def glance(self, msg): while True: try: Log.debug(2, 'Calling telepot.glance()') content_type, chat_type, chat_id = telepot.glance(msg) Log.debug( 2, 'Exiting telepot.glance() [content_type = {}, chat_type = {}, chat_id = {}]', content_type, chat_type, chat_id) break except telepot.exception.TelegramError as e: Log.error('Raise exception: {}', e.__name__) raise e except Exception as e: Log.error('Exception {} occurred', e.__name__) time.sleep(0.03) return (content_type, chat_type, chat_id)
def cleanup(self): Log.info('Runing cleanup(), this function will print winner list.') memberpoolx = memberpool(usage_str='Member') aftermemberpool = memberpool(Config.bot.other_store, 'New/Ignore member') for x in self.winner: Log.info('{} : {}', x, b64decode(memberpoolx.members[x])) memberpoolx.delete(x) aftermemberpool.write(x, 'null') Log.info('All clean up!')
def load(self): Log.debug(2, 'Entering group_cache_class.load()') self.__init__() with MainDatabase() as db: result = db.query("SELECT * FROM `welcomemsg`") for x in result: self.add(x) #if init: #syncLock.release() #kwargs['syncLock'].release() Log.info('Load welcomemsg table successful.') Log.debug(2, 'Exiting group_cache_class.load()')
def add(self, x, need_check_admin=True, not_found=False): if need_check_admin: try: result = { True: 1, False: 0 }.get( self.bot.getChatMember(x[0], self.bot.getid())['status']) except telepot.exception.BotWasKickedError: if not not_found: self.__db_del(x[0]) Log.info('Delete kicked chat:{}', x[0]) return except telepot.exception.TelegramError as e: if e[0] == 'Bad Request: chat not found': if not not_found: self.__db_del(x[0]) Log.warn('Delete not found chat:{}', x[0]) Log.warn( 'in group_cache_class.add() chat_id : {} not found', x[0]) elif 'Forbidden: bot is not a member of the' in e[0]: self.__db_del(x[0]) Log.warn('Delete kicked chat:{}', x[0]) else: raise e finally: result = 0 else: result = 0 self.g[x[0]] = { 'msg': x[1], 'is_admin': result, 'poemable': x[2], 'ignore_err': x[3], 'noblue': x[4], 'other': gc_base_switch(flag_name, x[5]), 'except': eval(b64decode(x[6])) }
def get(self, chat_id): try: Log.debug( 2, 'Calling group_cache_class.get() [chat_id in self.g = {}]', chat_id in self.g) Log.debug(2, '[self.g[{}] = {}]', chat_id, self.g[chat_id]) return self.g[chat_id] except KeyError: Log.error('Can\'t find {} in get()', chat_id) self.add((chat_id, None, 0, 1, 0, 0, b64encode(repr([]))), not_found=True) self.__db_add(chat_id) self.bot.sendMessage( chat_id, 'It\'s seems that database broken, please reset welcome message.' ) return {'msg': None}
def write(self, user_id, user_name): Log.debug(2, 'user_id is {}', user_id) with self.WriteLock: self.members[user_id] = user_name self.writeFile() Log.debug(2 ,'{}: Write {} to database successful', self.usage_str, user_id)
def main(): Log.info('Strat initializing....') Log.info('Debug enable: {}', Log.get_debug_info()[0]) Log.debug(1, 'Debug level: {}', Log.get_debug_info()[1]) bot_class() Log.info('Bot is now running!') if Config.git.switch: Log.info('Starting BackupSQL daemon') BackupSQL.sql_backup_daemon().start() Log.info('BackupSQL daemon is now running') while True: time.sleep(30)
def getid(self): Log.debug(2, 'Calling telepot_bot.getid() [return {}]', self.bot_id) return self.bot_id
def message_loop(self, on_message_function): Log.info('Starting message_loop()') self.bot.message_loop(on_message_function) Log.info('message_loop() is now started!')
def __init__(self, *args, **kwargs): Log.debug(2, 'Enter telepot_bot.__init__()') WAIT_TIME = 0.03 Log.debug(2, '[bot_token = {}]', Config.bot.bot_token) Log.info('Initializing bot settings...') self.bot = TelepotBotBase.Bot(Config.bot.bot_token) self.bot_id = int( Config.bot.bot_token[:Config.bot.bot_token.find(':')]) Log.info('Success login telegram bot with Token {}**************', Config.bot.bot_token[:Config.bot.bot_token.find(':') + 5]) Log.info('Loading telepot_bot.custom_init()') self.fail_with_md = None self.custom_init(*args, **kwargs) Log.info('Loading telepot_bot.custom_init() successful') Log.info('Bot settings initialized successful!') Log.debug(2, 'Exit telepot_bot.__init__()')
def delete(self, user_id): with self.WriteLock: self.members.pop(user_id) self.writeFile() Log.debug(2 ,'{}: Delete {} from database successful', self.usage_str, user_id)
def onMessage(self,msg): content_type, chat_type, chat_id = self.glance(msg) # Added process if content_type == 'new_chat_member' and msg['new_chat_participant']['id'] == self.getid(): self.gcache.add((chat_id, None, 0, 1, 0, 0, b64encode(repr([])))) with MainDatabase() as db: try: db.execute("INSERT INTO `welcomemsg` (`group_id`) VALUES (%d)"%chat_id) except MySQLdb.IntegrityError as e: if e[0] == 1062: Log.error('IntegrityError:{}', e[1]) else: traceback.print_exc() raise e self.sendMessage(chat_id,'Please use /setwelcome to set welcome message', reply_to_message_id=msg['message_id']) return # kicked process elif content_type == 'left_chat_member' and msg['left_chat_member']['id'] == self.getid(): self.gcache.delete(chat_id) return # Main process elif msg['chat']['type'] in group_type: if content_type == 'text': get_result = self.gcache.get(chat_id) result = botcommand_match.match(msg['text']) try: EntryCheck = 'entities' in msg and len(msg['entities']) > 0 and \ msg['entities'][0]['type'] == 'bot_command' except IndexError: EntryCheck = False Log.warn('Catched IndexError, msg={}', repr(msg)) if EntryCheck: if get_result['noblue'] and \ (not result or result.group(1) not in self.gcache.get(chat_id)['except']): delete_target_message(chat_id, msg['message_id']).start() # Match bot command check if command_match.match(msg['text']) or noparmcommand_match.match(msg['text']): if msg['from']['id'] == Config.bot.owner: result = re.match(r'^\/d( (-?\d+))?$', msg['text']) if result: operid = chat_id if result.group(1) is None else result.group(2) self.gcache.delete(operid) self.gcache.add((operid, None, 0, 1, 0, 0, b64encode(repr([]))), not_found=True) delete_target_message(chat_id, self.sendMessage(chat_id, 'Operaction completed!', reply_to_message_id=msg['message_id'])['message_id']).start() return result = re.match(r'^\/l$', msg['text']) if result: self.bot.leaveChat(chat_id) return result = setflag2command_match.match(msg['text']) if result: if str(result.group(2)) in flag_type: self.gcache.editflag((chat_id,str(result.group(2)),int(result.group(3)))) delete_target_message(chat_id, self.sendMessage(chat_id, 'Operation completed!', reply_to_message_id=msg['message_id'])['message_id']).start() # Match /poem command result = poemcommand_match.match(msg['text']) if result: if get_result['poemable']: result = self.pcache.get() if not result: result = b64encode('TBD') self.bot.sendChatAction(chat_id, 'typing') time.sleep(3) self.sendMessage(chat_id, b64decode(result), reply_to_message_id=msg['message_id']) return elif not get_result['ignore_err']: self.sendMessage(chat_id, 'Permission Denied.\n*你没有资格念他的诗,你给我出去*', parse_mode='Markdown', reply_to_message_id=msg['message_id']) return return # Other command need admin privilege, check it. if self.getChatMember(chat_id, msg['from']['id'])['status'] not in admin_type: if not get_result['ignore_err']: self.sendMessage(chat_id, 'Permission Denied.\n你没有权限,快滚', reply_to_message_id=msg['message_id']) if self.gcache.get_is_admin(chat_id): self.bot.restrictChatMember(chat_id, msg['from']['id'], until_date=msg['date']+60) return # Match /setwelcome command result = setcommand_match.match(msg['text']) if result: welcomemsg = str(result.group(2)) result = gist_match.match(welcomemsg) if result: r = urllib2.urlopen(welcomemsg) welcomemsg = r.read() r.close() if len(welcomemsg) > 4096: self.sendMessage(chat_id, "*Error*:Welcome message is too long.(len() must smaller than 4096)", parse_mode='Markdown', reply_to_message_id=msg['message_id']) return self.gcache.edit((chat_id, b64encode(welcomemsg))) self.sendMessage(chat_id, "*Set welcome message to:*\n%s"%welcomemsg, disable_web_page_preview=True, parse_mode='Markdown', reply_to_message_id=msg['message_id']) return # Match /clear command result = clearcommand_match.match(msg['text']) if result: self.gcache.edit((chat_id, None)) self.sendMessage(chat_id, "*Clear welcome message successfully!*", parse_mode='Markdown', reply_to_message_id=msg['message_id']) return # Match /reload command result = reloadcommand_match.match(msg['text']) if result : if msg['from']['id'] != Config.bot.owner: self.sendMessage(chat_id, "*Please contant owner to reload configuration*", parse_mode='Markdown', reply_to_message_id=msg['message_id']) return self.gcache.load() self.pcache.reload() self.sendMessage(chat_id, "*Reload configuration and poem completed!*", parse_mode='Markdown', reply_to_message_id=msg['message_id']) return # Match /setflag command result = setflagcommand_match.match(msg['text']) ''' result.group(2) is `flag name', result.group(3) is `flag value' ''' if result: self.bot.sendChatAction(chat_id, 'typing') if str(result.group(2)) not in flag_type: if not get_result['ignore_err']: self.sendMessage(chat_id, "*Error*: Flag \"%s\" not exist"%str(result.group(2)), parse_mode='Markdown', reply_to_message_id=msg['message_id']) return self.gcache.editflag((chat_id, str(result.group(2)), int(result.group(3)))) delete_target_message(chat_id, self.sendMessage(chat_id, "*Set flag \"%s\" to \"%d\" success!*"%(str(result.group(2)), int(result.group(3))), parse_mode='Markdown', reply_to_message_id=msg['message_id'])['message_id']).start() return result = exceptcommand_match.match(msg['text']) if result: if result.group(1) == 'd': if self.gcache.except_(chat_id, result.group(3), True): sendMessage_and_delete(chat_id, 'Delete except command success', msg['message_id']) else: sendMessage_and_delete(chat_id, 'Delete except command fail. (Is command in except list? Tips: try using /status to see more)', msg['message_id']) else: if self.gcache.except_(chat_id, result.group(3)): sendMessage_and_delete(chat_id, 'Add except command success', msg['message_id']) else: sendMessage_and_delete(chat_id, 'Add except command fail with excpet list too long.', msg['message_id']) return # Match /status command if statuscommand_match.match(msg['text']): delete_target_message(chat_id, self.sendMessage(chat_id, gen_status_msg(self.gcache.get(chat_id)), reply_to_message_id=msg['message_id'])['message_id']).start() return # Finally match /ping if pingcommand_match.match(msg['text']): self.sendMessage(chat_id, '*Current chat_id:* `{}`\n*Your id:* `{}`\n*Bot runtime: {}\nSystem load avg: {}*'.format( chat_id, msg['from']['id'], Log.get_runtime(), getloadavg()), parse_mode='Markdown', reply_to_message_id=msg['message_id'])['message_id'], 10) elif content_type in content_type_concerned: result = self.gcache.get(chat_id)['msg'] if result: self.sendMessage(chat_id, b64decode(result).replace('$name', username_splice_and_fix(msg['new_chat_participant'])), parse_mode='Markdown', disable_web_page_preview=True, reply_to_message_id=msg['message_id'])
def delete(self, chat_id): try: del self.g[chat_id] self.__db_del(chat_id) except KeyError: Log.error('Can\'t find {} in delete()', chat_id)