def edit(self, x): with MainDatabase() as db: if x[1]: db.execute( "UPDATE `welcomemsg` SET `msg` = '%s' WHERE `group_id` = %d" % (x[1], x[0])) else: db.execute( "UPDATE `welcomemsg` SET `msg` = NULL WHERE `group_id` = %d" % x[0]) self.g[x[0]]['msg'] = x[1]
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 editflag(self, x): ''' x must be `tuple', x structure: (chat_id, flag_string_name, flag_value) ''' #Log.debug(1, 'x = {}, x in flag_name = {}, flag_name = {}', repr(x), repr(x in flag_name), repr(flag_name)) if x[1] in flag_name: if self.g[x[0]]['other'][x[1]] == x[2]: return self.g[x[0]]['other'][x[1]] = x[2] with MainDatabase() as db: db.execute( "UPDATE `welcomemsg` set `other` = {} WHERE `group_id` = {}" .format(int(self.g[x[0]]['other']), x[0])) else: if self.g[x[0]][x[1]] == x[2]: return self.g[x[0]][x[1]] = x[2] with MainDatabase() as db: db.execute( "UPDATE `welcomemsg` SET `%s` = %d WHERE `group_id` = %d" % (x[1], x[2], x[0]))
def except_(self, chat_id, command, is_del=False): if is_del: try: self.g[chat_id]['except'].remove(command) except ValueError: return False else: self.g[chat_id]['except'].append(command) if len(b64encode(repr(self.g[chat_id]['except']))) > 498: self.g[chat_id]['except'].remove(command) return False self.g[chat_id]['except'] = list(set(self.g[chat_id]['except'])) with MainDatabase() as db: db.execute( "UPDATE `welcomemsg` SET `except` = '{}' WHERE `group_id` = {}" .format(b64encode(repr(self.g[chat_id]['except'])), chat_id)) return True
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 load(self): with MainDatabase() as db: result = db.query("SELECT * FROM `poem`") for x in result: self.__add(x[0])
def __db_add(self, chat_id): with MainDatabase() as db: db.execute("INSERT INTO `welcomemsg` (`group_id`) VALUES (%d)" % chat_id)
def __db_del(self, chat_id): with MainDatabase() as db: db.execute("DELETE FROM `welcomemsg` WHERE `group_id` = %d" % (chat_id))