Exemplo n.º 1
0
	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))
Exemplo n.º 2
0
 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 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]))
     }
Exemplo n.º 4
0
	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'])